Problem to update clockwidget - Android Software/Hacking General [Developers Only]

I have try to develop a clock widget for me and it works not correctly then when I use a other app I think the clock stopps to count I think the problem is when I switch the app. I hope you can help me.
HTML:
public class WidgetManager extends AppWidgetProvider {
[user=439709]@override[/user]
public void onUpdate(final Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);
final Date date = new Date();
final RemoteViews remote = new RemoteViews(context.getPackageName(),R.layout.widgetlayout);
Intent openActivity = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, openActivity, 0);
remote.setOnClickPendingIntent(R.id.button, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, remote);
remote.setTextViewText(R.id.hour, getHour());
remote.setTextViewText(R.id.minute, getMinute());
remote.setTextViewText(R.id.date, getDate());
updateText(context, remote);
runUpdater(context, remote);
}
[user=439709]@override[/user]
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
}
public void updateText(Context context, RemoteViews remoteViews){
ComponentName widgetcomp = new ComponentName(context, WidgetManager.class);
AppWidgetManager.getInstance(context).updateAppWidget(widgetcomp, remoteViews);
}
public void runUpdater(final Context context, final RemoteViews remote){
final Handler handler = new Handler();
final Date date = new Date();
handler.postDelayed(new Runnable() {
[user=439709]@override[/user]
public void run() {
remote.setTextViewText(R.id.hour, getHour());
remote.setTextViewText(R.id.minute, getMinute());
remote.setTextViewText(R.id.date, getDate());
updateText(context, remote);
handler.removeCallbacks(this);
runUpdater(context, remote);
}
}, 1000); //update every second
}
public String getHour(){
DateFormat dfTime = new SimpleDateFormat("HH");
String time = dfTime.format(Calendar.getInstance().getTime());
return time;
}
public String getMinute(){
DateFormat dfTime = new SimpleDateFormat("mm");
String time = dfTime.format(Calendar.getInstance().getTime());
return time;
}
public String getDate(){
DateFormat dfTime = new SimpleDateFormat("E, d MMMM");
String time = dfTime.format(Calendar.getInstance().getTime());
return time;
}
}

Related

[Q] How do i capped my maximum directory storage space in SD? PLEASE HELP!!!

Question 1: Presumingly i wanted to allocate only 1GB of space to store my videos in a particular self declared directory how should i do it?
Question 2: And i wanted my directory to capped at 1GB after which how is it going to auto-delete the oldest video file in that directory once its about to reach 1GB?
Sorry i'm kinna new in java and android and currently creating an car blackbox app can someone help me... Thanks
This is what I have tried so far can someone tell me how should i implement the above function into my mainActivity:
Code:
public class CameraTest extends Activity implements SurfaceHolder.Callback {
private static final String TAG = "Exception";
public static SurfaceView surfaceView;
public static SurfaceHolder surfaceHolder;
public static Camera camera;
public static boolean previewRunning;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
surfaceView = (SurfaceView)findViewById(R.id.surface_camera);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
Button btnStart = (Button) findViewById(R.id.button4);
btnStart.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
startService(new Intent(getApplicationContext(), ServiceRecording.class));
}
});
Button btnStop = (Button) findViewById(R.id.button5);
btnStop.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
stopService(new Intent(getApplicationContext(), ServiceRecording.class));
}
});
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
if (camera != null) {
Camera.Parameters params = camera.getParameters();
camera.setParameters(params);
}
else {
Toast.makeText(getApplicationContext(), "Camera not available!", Toast.LENGTH_LONG).show();
finish();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if (previewRunning) {
camera.stopPreview();
}
Camera.Parameters p = camera.getParameters();
p.setPreviewSize(320, 240);
p.setPreviewFormat(PixelFormat.JPEG);
camera.setParameters(p);
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
previewRunning = true;
}
catch (IOException e) {
Log.e(TAG,e.getMessage());
e.printStackTrace();
}
}
@Override
public void onResume(){
super.onResume();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder){
camera.stopPreview();
previewRunning = false;
camera.release();
}
}
My RecordingService.java Service file
Code:
public class ServiceRecording extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
private Camera camera;
private boolean recordingStatus;
private MediaRecorder mediaRecorder;
private final int maxDurationInMs = 20000;
private static final String TAG = "Exception";
@Override
public void onCreate() {
super.onCreate();
recordingStatus = false;
camera = CameraTest.camera;
surfaceView = CameraTest.surfaceView;
surfaceHolder = CameraTest.surfaceHolder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if (recordingStatus == false)
startRecording();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
stopRecording();
//camera.stopPreview();
recordingStatus = false;
//camera.release();
}
public boolean startRecording(){
try {
Toast.makeText(getBaseContext(), "Recording Started", Toast.LENGTH_SHORT).show();
try{
camera.unlock();
}
catch(Exception e){
camera.reconnect();
}
mediaRecorder = new MediaRecorder();
mediaRecorder.setCamera(camera);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
mediaRecorder.setMaxDuration(maxDurationInMs);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
//mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH_mm_ss");
Date date = new Date();
File directory = new File(Environment.getExternalStorageDirectory() + "/VideoList");
if(!(directory.exists()))
directory.mkdir();
File FileSaved = new File(Environment.getExternalStorageDirectory() + "/VideoList", dateFormat.format(date) + ".3gp");
mediaRecorder.setOutputFile(FileSaved.getPath());
mediaRecorder.setVideoSize(surfaceView.getWidth(),surfaceView.getHeight());
//mediaRecorder.setVideoFrameRate(videoFramesPerSecond);
mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
mediaRecorder.prepare();
mediaRecorder.start();
recordingStatus = true;
return true;
}
catch (IllegalStateException e) {
Log.d(TAG,e.getMessage());
e.printStackTrace();
return false;
}
catch (IOException e) {
Log.d(TAG,e.getMessage());
e.printStackTrace();
return false;
}
}
public void stopRecording() {
Toast.makeText(getBaseContext(), "Recording Stopped", Toast.LENGTH_SHORT).show();
mediaRecorder.stop();
try {
camera.reconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
recordingStatus = false;
}
}
Anyone can help please...
I've tried my best to do my coding but i'm really in a desperate bit to get some help from you guys here... Could someone please help me, not that i'm lazy or what to do the coding myself but its just that i'm really bad in programming and new to android but yet force to do this project so decided to ask for help from you guys here...
I found this online but it seems that it answer part of my question isn't it but i don't seem to know how to integrate it into my codes... Can someone help me with this problem?
Code:
private static long dirSize(File dir) {
long result = 0;
Stack<File> dirlist= new Stack<File>();
dirlist.clear();
dirlist.push(dir);
while(!dirlist.isEmpty())
{
File dirCurrent = dirlist.pop();
File[] fileList = dirCurrent.listFiles();
for (int i = 0; i < fileList.length; i++) {
if(fileList[i].isDirectory())
dirlist.push(fileList[i]);
else
result += fileList[i].length();
}
}
return result;
}
Could someone guide me along with the above codes??

[Q] How can I create a white list of Apps?

Hi, I am developping a home screen app, and I want only certain apps to be able tu be launched from my home screen.
I want to do it exactly like Surelock:
When the user tries to open an app that doesn't belong to my list of accepted apps, he should receive a toast saying something like example: "com.android.settings blocked by this app".
I need that type of security, I came across a piece of code on the web, but it does not work...
Could you help me out either by suggesting something new or by helping me understand and fix this one?
public class MonitorService extends Service {
private Handler handler;
Runnable runnable;
@override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
handler = new Handler();
runnable = new Runnable() {
@override
public void run() {
new Thread(new Runnable() {
@override
public void run() {
ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> taskInfo = am
.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
String currentActivityName=componentInfo.getClassName();
String packageName=componentInfo.getPackageName();
if(whitelist.contains(currentActivityName)){
Intent launchIntent = new Intent();
launchIntent.setComponent(new ComponentName(blockActivityPackageName,
blockActivityName));
launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(launchIntent);
}
}
}).start();
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(runnable, 1000);
}
@override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
@override
public IBinder onBind(Intent intent) {
return null;
}
@override
public void onDestroy() {
super.onDestroy();
Intent intent = new Intent(this, MonitorService.class);
startService(intent);
}
@override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}}

[Q] Android: Why are my images coming in so blurry?

I have a Slideshow for the Home Page of my app looks sorta like the Houzz apps Home Page, were it displays a new image daily. But their is one issue I am having is that all of my images are coming in so blurry. I've checked the Resolution and it shouldn't be that blurry for no reason at all. I've tried changing setScaleType such as switching it too CENTER, CENTER_CROP, and Etc... None of those seemed to work. I have tried everything too my knowledge and now I am stuck, Below are some of my relevant source code in order too successfully help me out on this issue.
This is the Home.java this is linked/runs functions of homebck.xml:
Code:
public class Home extends Fragment {
private final int FileUpload = 100;
public static final String URL =
private Context context;
private ImageView m_imageInformation;
private ImageView m_imageSave;
private ImageView m_imageWallPaper;
private ViewPager m_viewPager;
private ImageAdapter m_imageAdapter;
private ArrayList<ImageView> m_imageViewList;
private int[] m_galleryImages = new int[]{
R.drawable.ic_share,
R.drawable.ic_share,
R.drawable.ic_share
};
public static String popup_status = "";
public static File path = new File(Environment.getExternalStorageDirectory() + "");
public static Item[] fileList;
public static String chosenFile;
public static Boolean firstLvl = true;
ListAdapter adapter;
public static ArrayList<String> str = new ArrayList<String>();
public String dbPath = "/data/data/com.Celebration/";
private AboutPopup m_aboutPopup;
private InformationPopup m_informationPopup;
public static String ss;
public static List<DBManager.ImageModel> m_images;
public ImageLoader imageLoader;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// return super.onCreateView(inflater, container, savedInstanceState);
// super.onCreateView(inflater, container, savedInstanceState);
context = getActivity();
View rootView = inflater.inflate(R.layout.homebck, container, false);
m_viewPager = (ViewPager) rootView.findViewById(R.id.view_pager);
m_imageInformation = (ImageView) rootView.findViewById(R.id.image_information);
m_imageSave = (ImageView) rootView.findViewById(R.id.image_save);
m_imageWallPaper = (ImageView) rootView.findViewById(R.id.image_wallpaper);
initView();
m_imageInformation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Globals.imageNumber = m_viewPager.getCurrentItem();
m_informationPopup.showAtLocation(m_viewPager, 0, 0);
}
});
m_imageSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
loadFileList();
onCreateDialog(100);
}
});
m_imageWallPaper.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
//sendIntent.setAction(Intent.ACTION_CHOOSER);
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "");
sendIntent.putExtra(Intent.EXTRA_EMAIL, "");
sendIntent.setType("text/plain");
sendIntent.putExtra(Intent.EXTRA_TEXT, "Hello, I wanted to invite you to join this app with me! It's a guide about Celebration, FL. Come see ");
sendIntent.setType("text/plain");
//Sipdroid.this.startActivity(sendIntent);*/
context.startActivity(Intent.createChooser(sendIntent, "Tell a friend via..."));
}
});
return rootView;
}
public void initView(){
m_imageViewList = new ArrayList<ImageView>();
m_aboutPopup = new AboutPopup(getActivity());
m_informationPopup = new InformationPopup(getActivity());
Globals.m_dbMan = new DBManager(context);
m_images = Globals.m_dbMan.getImageListData();
m_imageViewList.clear();
if(m_images != null){
for (int i = m_images.size() - 1 ; i >= 0; i--) {
ImageView imageView = new ImageView(context);
setImage(imageView, i);
m_imageViewList.add(imageView);
}
}else{
ImageView imageView = new ImageView(context);
imageLoader = new ImageLoader(context);
imageLoader.DisplayImage(URL, imageView);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
m_imageViewList.add(imageView);
}
m_imageAdapter = new ImageAdapter(m_imageViewList);
m_viewPager.setAdapter(m_imageAdapter);
}
public void setImage(ImageView m_imgView, int currentIndex)
{
File imgFile = new File(m_images.get(currentIndex).imagePath);
//Uri uri = Uri.fromFile(new File(lstImage.get(currentIndex).imagePath));
Bitmap myBitmap = decodeFile(imgFile);
m_imgView.setImageBitmap(myBitmap);
m_imgView.setAdjustViewBounds(true);
m_imgView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
}
public static Bitmap decodeFile(File f){
Bitmap b = null;
int IMAGE_MAX_SIZE = 1000;
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
FileInputStream fis;
try {
fis = new FileInputStream(f);
BitmapFactory.decodeStream(fis, null, o);
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int scale = 1;
if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
int maxwh = Math.max(o.outWidth,o.outHeight);
while(maxwh / scale > IMAGE_MAX_SIZE)
scale *= 2;
}
Log.d("twinklestar.containerrecog", "width: " + o.outWidth + "height: " + o.outHeight + "scale:" + scale);
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
fis = new FileInputStream(f);
b = BitmapFactory.decodeStream(fis, null, o2);
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return b;
}
/* @Override
public void onClick(View v) {
Log.d("onclick", "ok");
switch (v.getId()){
case R.id.image_information:
{
Toast.makeText(context, "ok", Toast.LENGTH_SHORT).show();
break;
}
case R.id.image_save:
{
// loadFileList();
onCreateDialog(100);
break;
}
case R.id.image_wallpaper:
{
((Activity)context).finish();
break;
}
default:
break;
}
}*/
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
if (fileList == null) {
Log.e("TAG", "No files loaded");
dialog = builder.create();
return dialog;
}
switch (id) {
case FileUpload:
builder.setTitle("Select a Folder to save");
builder.setPositiveButton("download", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
ImageView image = new ImageView(context);
imageLoader = new ImageLoader(context);
Globals.downloadFlag = true;
Globals.downlaodForSaving = true;
Globals.saveFolder = path.toString();
imageLoader.DisplayImage(URL, image);
}
});
builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
});
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
chosenFile = fileList[which].file;
File sel = new File(path + "/" + chosenFile);
if (sel.isDirectory()) {
firstLvl = false;
// Adds chosen directory to list
str.add(chosenFile);
fileList = null;
path = new File(sel + "");
loadFileList();
dialog.dismiss();
onCreateDialog(FileUpload);
Log.d("TAG", path.getAbsolutePath());
}
// Checks if 'up' was clicked
else if (chosenFile.equalsIgnoreCase("up") && !sel.exists()) {
// present directory removed from list
String s = str.remove(str.size() - 1);
// path modified to exclude present directory
path = new File(path.toString().substring(0,
path.toString().lastIndexOf(s)));
fileList = null;
// if there are no more directories in the list, then
// its the first level
if (str.isEmpty()) {
firstLvl = true;
}
loadFileList();
//UploadFragment.this.getActivity().removeDialog(DIALOG_LOAD_FILE);
dialog.dismiss();
onCreateDialog(FileUpload);
//UploadFragment.this.getActivity().showDialog(DIALOG_LOAD_FILE);
Log.d("TAG", path.getAbsolutePath());
}
// File picked
else {
// Perform action with file picked
//Toast.makeText(UploadFragment.this.getActivity(), chosenFile, Toast.LENGTH_SHORT).show();
ss = path.getAbsolutePath() + "/" + chosenFile;
String extension = chosenFile.substring(chosenFile.indexOf(".") + 1);
if (extension.equals("png") || extension.equals("jpg") || extension.equals("bmp")) {
dialog.dismiss();
m_aboutPopup.showAtLocation(m_viewPager, 0, 0);
// onUpload(ss,chosenFile);
} else
Toast.makeText(getActivity(), "This is not image file!", Toast.LENGTH_SHORT).show();
}
}
});
break;
}
dialog = builder.show();
return dialog;
}
Below this a SNIPPET/part of the MainActivity.java *hint URL1,2,3,4... Grabs the URL that is put into String:
Code:
public static String des;
public String myurl = null;
public class AboutPopup implements View.OnClickListener {
public View parent;
public PopupWindow popupWindow;
public ListView m_listHolder;
public EditText m_editDescription;
public Button m_btnUpload;
public DatePicker dp;
public TimePicker tp;
private PendingIntent pendingIntent;
private Spinner spinner;
private ImageView imageView;
private TextView selectImageurl;
private TextView imageDescription;
public AboutPopup(Context paramContext) {
this.parent = ((LayoutInflater) paramContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.settting_popup, null);
//this.parent.findViewBy)
this.popupWindow = new PopupWindow(this.parent, ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT, true);
this.m_editDescription = (EditText) parent.findViewById(R.id.setting_description);
this.m_btnUpload = (Button) parent.findViewById(R.id.btn_setting_show);
m_btnUpload.setOnClickListener(this);
selectImageurl = (TextView) parent.findViewById(R.id.select_imageurl);
imageDescription = (TextView) parent.findViewById(R.id.image_description);
selectImageurl.setTextSize(convertFromDp(24));
imageDescription.setTextSize(convertFromDp(24));
dp = (DatePicker) parent.findViewById(R.id.datePicker);
tp = (TimePicker) parent.findViewById(R.id.timePicker);
dp.setCalendarViewShown(false);
imageView = (ImageView)parent.findViewById(R.id.setting_image);
spinner = (Spinner) parent.findViewById(R.id.setting_spinner);
String[] platforms = paramContext.getResources(). getStringArray(R.array.dev_platforms);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(paramContext, R.layout.spinner_item, platforms);
spinner.setAdapter(adapter);
// If you want to continue on that TimeDateActivity
// If you want to go to new activity that code you can also write here
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch(position){
case 0:
myurl = URL;
break;
case 1:
myurl = URL1;
break;
case 2:
myurl = URL3;
break;
case 3:
myurl = URL4;
break;
case 4:
break;
}
if(myurl != null){
imageLoader = new ImageLoader(MainActivity.this);
imageLoader.DisplayImage(myurl, imageView);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void showAtLocation(View pView, int left, int top) {
this.popupWindow.setOutsideTouchable(true);
this.popupWindow.setTouchable(true);
this.popupWindow.update();
popupWindow.setBackgroundDrawable(new BitmapDrawable());
popupWindow.setAnimationStyle(R.style.PopupAnimation);
popupWindow.setWidth((int) (pView.getWidth() * 0.95));
popupWindow.setHeight((int) (pView.getHeight()));
popupWindow.showAtLocation(pView, Gravity.CENTER_VERTICAL, 0, 0);
// this.popupWindow.showAtLocation(pView, Gravity.CENTER, left, top);
}
public void hide() {
this.popupWindow.dismiss();
}
public boolean isVisible() {
return this.popupWindow.isShowing();
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_setting_show: {
imageLoader = new ImageLoader(MainActivity.this);
Globals.downloadFlag = true;
imageLoader.DisplayImage(myurl, imageView);
ss = path.getAbsolutePath() + "/" + ImageLoader.fname;
des = this.m_editDescription.getText().toString();
Globals.alarmFileName[Globals.alarmNumber] = ImageLoader.fname;
Globals.alarmDescription[Globals.alarmNumber] = des;
Globals.alarmNumber = Globals.alarmNumber + 1;
String strDateTime = dp.getYear() + "-" + (dp.getMonth() + 1) + "-" + dp.getDayOfMonth();
Intent Intent = new Intent(MainActivity.this, AlarmReceiver.class);
Intent.putExtra("id",Globals.alarmNumber-1);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, Intent, 0);
Calendar cal = Calendar.getInstance();
cal.set(dp.getYear(), dp.getMonth(), dp.getDayOfMonth(),tp.getCurrentHour(), tp.getCurrentMinute());
Calendar current = Calendar.getInstance();
if(current.get(Calendar.YEAR) > cal.get(Calendar.YEAR) && current.get(Calendar.MONTH) > cal.get(Calendar.MONTH) && current.get(Calendar.DATE) > cal.get(Calendar.DATE)){
Toast.makeText(MainActivity.this, "Please select other time", Toast.LENGTH_SHORT).show();
return;
}
// schedule for every 30 seconds
alarm.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
if (des == null) {
Toast.makeText(MainActivity.this, "Input description in..", Toast.LENGTH_SHORT).show();
return;
} else {
popupWindow.dismiss();
}
}
break;
}
}
}
homebck.xml:
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="..."
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/homefragment"
android:background="@color/white">
<android.support.v4.view.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="10" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center_horizontal"
android:layout_weight="1">
<ImageView
android:id="@+id/image_information"
android:layout_width="0dp"
android:layout_height="match_parent"
android:src="@drawable/ic_information"
android:layout_weight="1" />
<ImageView
android:id="@+id/image_save"
android:layout_width="0dp"
android:layout_height="match_parent"
android:src="@drawable/ic_save"
android:layout_weight="1"
/>
<ImageView
android:id="@+id/image_wallpaper"
android:layout_width="0dp"
android:layout_height="match_parent"
android:src="@drawable/ic_share"
android:layout_weight="1"/>
</LinearLayout>
</LinearLayout>

Not working context menu item in fragment

Code:
public class ThreeFragment extends Fragment {
public View ThreeFragmentView = null;
public static TextView internalMemoryInfo;
public static Button IntBtn;
public ThreeFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (ThreeFragmentView == null) ThreeFragmentView = inflater.inflate(R.layout.fragment_three, container, false);
internalMemoryInfo = (TextView) ThreeFragmentView.findViewById(R.id.textViewInternalMemoryInfo);
IntBtn = (Button) ThreeFragmentView.findViewById(R.id.InternalBtn);
return ThreeFragmentView;
}
public static void showText(String text) {
internalMemoryInfo.setText(text);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
registerForContextMenu(IntBtn);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
switch (v.getId()){
case R.id.InternalBtn:
menu.setHeaderTitle("Internal Memory Menu");
menu.add(0, ClearCacheMet, 0, "Clear Cache");
menu.add(0, Common, 0, "Go to Common Tab");
menu.add(0, ITEM_CANCEL, 0, "Cancel");
break;
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case ClearCacheMet:
ClearCache(); <-------This not working
break;
case Common:
tabLayout.getTabAt(0).select(); <-------This working
break;
case ITEM_CANCEL:
ins.closeContextMenu(); <-------This working
break;
}
return true;
}
public static boolean deleteDir(File dir){
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
}
public static void ClearCache() {
File cache = ins.getCacheDir();
File appDir = new File(cache.getParent());
if (appDir.exists()) {
String[] children = appDir.list();
for (String s : children) {
if (!s.equals("lib")) {
deleteDir(new File(appDir, s));
}
}
}
try{
/*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
((ActivityManager) ins.getSystemService(Context.ACTIVITY_SERVICE)).clearApplicationUserData();
} else {*/
File externalcache = ins.getExternalCacheDir();
File externalappDir = new File(externalcache.getParent());
if (externalappDir.exists()) {
String[] children = externalappDir.list();
for (String s : children) {
if (!s.equals("lib")) {
deleteDir(new File(externalappDir, s));
}
}
} else {
Log.d(TAG, "No externalappDir");
}
/*}*/
} catch (Exception e) {
Log.d(TAG, "MainActivity in ClearCache");
}
}
I have fragment(ThreeFragment) with button(InternalBtn) that have a context menu. Context menu registered with registerForContextMenu(IntBtn); Menu item ClearCacheMet not working. I cannot see neither Toast.makeText().show(); nor Log.d(TAG, "ClearCache"); Common and ITEM_CANCEL items working. I cannot understand why? Please help me.
Toast.makeText(getActivity(), "Called !", Toast.LENGTH_SHORT).show(); not called in ClearCache() function. ClearCacheMet and Common were initialized in other fragment.
public class OneFragment extends Fragment {
public View OneFragmentView = null;
public static final int Common = 25;
public static final int ClearCacheMet = 50;

Is RecyclerView refreshed when AlertDialog's positive button gets pressed

My MainActivity has a RecyclerView adapter, and data to this RecyclerView is added through a AlertDialog which passes the entered text to the MainActivity. The recycler view gets refreshed somehow when the positive button in the dialog is pressed even though I never call notifyItemInserted() or notifyDatasetChange() after passing the new input. I want to know how this happens, my guess is the recyclerview is somehow refreshed after the positive button is pressed in the dialog box.
Custom AlertDialog Code:
Code:
public class CustomDialog extends AppCompatDialogFragment {
OnNoteAddedListener onNoteAddedListener;
public interface OnNoteAddedListener {
public void onClick(String note);
}
public CustomDialog(OnNoteAddedListener onNoteAddedListener) {
this.onNoteAddedListener = onNoteAddedListener;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
final LayoutInflater inflater = getActivity().getLayoutInflater();
final View dialogLayout = inflater.inflate(R.layout.dialog_box, null);
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(dialogLayout).setPositiveButton("Ok", new DialogInterface.OnClickListener() {@Override
public void onClick(DialogInterface dialog, int id) {
EditText addNote = dialogLayout.findViewById(R.id.note_text);
String note = addNote.getText().toString();
onNoteAddedListener.onClick(note);
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
CustomDialog.this.getDialog().cancel();
}
});
return builder.create();
}
}
Adapter code:
Code:
class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>
{
private static final String TAG = "RecyclerViewAdapter";
private List<String> notesList;
private Context mContext;
private SendPositionConnector sendPositionConnector;
public interface SendPositionConnector
{
public void sendPosition(int position);
}
public RecyclerViewAdapter(List<String> notesList, Context mContext)
{
this.notesList = notesList;
this.mContext = mContext;
this.sendPositionConnector = (MainActivity)mContext;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_listitem, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, final int position)
{
Log.d(TAG, "onBindViewHandler: called");
viewHolder.noteContent.setText(notesList.get(position));
viewHolder.parentLayout.setOnLongClickListener(new View.OnLongClickListener(){
@Override
public boolean onLongClick(View view)
{
Log.d(TAG, "onLongClick: long clicked on");
sendPositionConnector.sendPosition(position);
return false;
}
});
}
@Override
public int getItemCount()
{
return notesList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder
{
TextView noteContent;
RelativeLayout parentLayout;
ImageView bullet;
public ViewHolder(@NonNull View itemView)
{
super(itemView);
bullet = itemView.findViewById(R.id.bullet);
noteContent = itemView.findViewById(R.id.text_content);
parentLayout = itemView.findViewById(R.id.parent_layout);
}
}
}
Main Activity:
Code:
public class MainActivity extends AppCompatActivity implements RecyclerViewAdapter.SendPositionConnector
{
private static final String TAG = "MainActivity";
private List<String> notesList = new ArrayList<>();
private RecyclerView recyclerView;
private RecyclerViewAdapter adapter;
private int position;
public AgentAsyncTask agentAsyncTask;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.my_recycler_view);
registerForContextMenu(recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
agentAsyncTask = new AgentAsyncTask(notesList, getApplicationContext(), true, new AgentAsyncTask.OnRead(){
@Override
public void onRead(List<String> notesList)
{
if(!notesList.isEmpty())
MainActivity.this.notesList = notesList;
adapter = new RecyclerViewAdapter(notesList, MainActivity.this);
recyclerView.setAdapter(adapter);
}
});
agentAsyncTask.execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.add_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle item selection
switch (item.getItemId())
{
case R.id.add_note:
showDialogBox(item);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onStop()
{
super.onStop();
new AgentAsyncTask(notesList, getApplicationContext(), false, new AgentAsyncTask.OnRead(){
@Override
public void onRead(List<String> notesList)
{
if(!notesList.isEmpty())
MainActivity.this.notesList = notesList;
}
}).execute();
}
@Override
protected void onDestroy()
{
super.onDestroy();
}
private boolean showDialogBox(MenuItem menuItem)
{
AppCompatDialogFragment dialogFragment = new CustomDialog(new CustomDialog.OnNoteAddedListener(){
@Override
public void onClick(String note)
{
Log.d(TAG, "onClick: "+ note);
notesList.add(note);
}
});
dialogFragment.show(getSupportFragmentManager(),"Adding");
return true;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
@Override
public boolean onContextItemSelected(MenuItem menuItem)
{
switch(menuItem.getItemId())
{
case R.id.delete:
notesList.remove(position);
adapter.notifyItemRemoved(position);
adapter.notifyItemRangeChanged(position, notesList.size());
return true;
default:
return false;
}
}
@Override
public void sendPosition(int position)
{
this.position = position;
}
private static class AgentAsyncTask extends AsyncTask<Void, Void, List<String>>
{
private List<String> notesList;
private boolean flag;
OnRead onRead;
Context context;
AppDataBase dataBase;
private static final String TAG = "AgentAsyncTask";
public interface OnRead
{
public void onRead(List<String> notesList);
}
private AgentAsyncTask(List<String> notesList,Context context,boolean flag, OnRead onRead)
{
this.notesList = notesList;
this.onRead = onRead;
this.flag = flag;
this.context = context;
}
@Override
protected List<String> doInBackground(Void... params)
{
dataBase = Room.databaseBuilder(context, AppDataBase.class, "database-name").build();
if(!flag)
{
Gson gson = new Gson();
Type type = new TypeToken<List<String>>() {}.getType();
String json = gson.toJson(notesList, type);
Log.d(TAG, "doInBackground: "+json);
Notes notes = new Notes();
notes.setNoteContent(json);
notes.setUid(1);
dataBase.notesDao().insertNotes(notes);
return notesList;
}
else
{
Gson gson = new Gson();
String notesListContent = dataBase.notesDao().getNotes();
if(dataBase.notesDao().getCount() != 0)
{
notesList = gson.fromJson(notesListContent, new TypeToken<List<String>>()
{
}.getType());
}
else
{
return notesList;
}
return notesList;
}
}
@Override
protected void onPostExecute(List<String> notesList)
{
super.onPostExecute(notesList);
if(flag)
onRead.onRead(notesList);
}
}
}

Categories

Resources