[Q] Problem when sending string to server - General Questions and Answers

Hi i am new to android developing. I don't know is this the right section to post but i really need help on this. My app is a remote control and and it has to send strings to the server (PC) by clicking the buttons. Somehow my app crashes when i click the button . I cant figure out the problem. Can anyone help me please?? .
here I'm pasting the code:
Code:
public class MyAppActivity extends Activity {
/** Called when the activity is first created. */
Button mButton;
EditText mEdit;
TextView mTextView;
String ip;
Socket s;
InputStream is;
InputStreamReader isr;
BufferedReader br;
DataOutputStream os;
//PrintWriter pw;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.addip);
mButton = (Button) findViewById(R.id.button1);
mEdit = (EditText) findViewById(R.id.editText1);
mTextView = (TextView) findViewById(R.id.tConnectStatus);
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String ip = mEdit.getText().toString();
try {
s = new Socket(ip, 2222);
is = s.getInputStream();
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
os = new DataOutputStream(s.getOutputStream());
//pw = new PrintWriter(os, true);
// s.close();
} catch (Exception ex) {
// System.out.println(ex);
CharSequence statusMesg = "Please Enter the Correct IP ";
mTextView.setText(statusMesg);
}
// Wificlient conState = new Wificlient();
if (s.isConnected()) {
CharSequence statusMesg = "Connected";
mTextView.setText(statusMesg);
Intent startAcontroller = new Intent(
"my.hasham.joy.app.ACONTROLLER");
startActivity(startAcontroller);
} else {
CharSequence statusMesg = "Please Enter the Correct IP ";
mTextView.setText(statusMesg);
// finish();
}
// Intent startAcontroller = new
// Intent("my.hasham.joy.app.ACONTROLLER");
// startActivity(startAcontroller);
}
});
}
public void sendForward(String cmd) throws IOException {
os.writeUTF(cmd);
}
public void sendBackward(String cmd) throws IOException {
os.writeUTF(cmd);
}
public void sendLeft(String cmd) throws IOException {
os.writeUTF(cmd);
}
public void sendRight(String cmd) throws IOException {
os.writeUTF(cmd);
}
public void sendStart(String cmd) throws IOException {
os.writeUTF(cmd);
}
public void sendSelect(String cmd) throws IOException {
os.writeUTF(cmd);
}
public void sendB(String cmd) throws IOException {
os.writeUTF(cmd);
}
public void sendA(String cmd) throws IOException {
os.writeUTF(cmd);
}
}
and the other activity:
Code:
public class Acontroller extends Activity {
Button bForward;
Button bBackward;
Button bRight;
Button bLeft;
Button bSelect;
Button bStart;
Button bB;
Button bA;
public MyAppActivity command = new MyAppActivity();
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.nesskin);
bForward = (Button) findViewById(R.id.bForward);
bBackward = (Button) findViewById(R.id.bBackward);
bRight = (Button) findViewById(R.id.bRight);
bLeft = (Button) findViewById(R.id.bLeft);
bSelect = (Button) findViewById(R.id.bSelect);
bStart = (Button) findViewById(R.id.bStart);
bA = (Button) findViewById(R.id.bA);
bB = (Button) findViewById(R.id.bB);
bForward.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
command.sendForward("forward");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
bBackward.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
// MyAppActivity command = new MyAppActivity();
try {
command.sendBackward("backward");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
bLeft.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
// MyAppActivity command = new MyAppActivity();
try {
command.sendLeft("Left");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
bRight.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
// MyAppActivity command = new MyAppActivity();
try {
command.sendRight("right");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
bSelect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
// MyAppActivity command = new MyAppActivity();
try {
command.sendSelect("select");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
bStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
// MyAppActivity command = new MyAppActivity();
try {
command.sendStart("start");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
bA.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
// MyAppActivity command = new MyAppActivity();
try {
command.sendA("a");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
bB.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
// MyAppActivity command = new MyAppActivity();
try {
command.sendB("b");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
Please if anyone can help me . I really need to get this done.

Related

Save calculator result problem

Here's where the button is pressed:
btnMP.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
memNum = memNum + Double.parseDouble(txtCalc.getText().toString());
operator = 0; }
});
Here's a thingie I hammered together from parts:
// Save MEMORY
public void WriteMemory(OnClickListener onClickListener, double
memNum){
File sdcard = Environment.getExternalStorageDirectory();
File destinationdir = new File(sdcard,"/download/calculator");
destinationdir.mkdir();
File destinationfile = new File(destinationdir,"memory.dat");
FileOutputStream fOut = null;
OutputStreamWriter osw = null;
try{
destinationfile.createNewFile();
fOut = new FileOutputStream(destinationfile);
osw = new OutputStreamWriter(fOut);
osw.write((int) memNum);
osw.flush();
Toast.makeText((Context) onClickListener, "Memory
saved",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
e.printStackTrace();
// Toast.makeText((Context) onClickListener, "Memory not
saved",Toast.LENGTH_SHORT).show();
}
finally {
try {
osw.close();
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is called by inserting WriteMemory(this,memNum); in the button
routine thusly:
btnMP.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
memNum = memNum + Double.parseDouble(txtCalc.getText().toString());
operator = 0; }
WriteMemory(this,memNum);
});
The file is created but only a 0 is written in it. What's missing?
Brian

Why can't my GUI return back to recording mode despite having service?

Hi i'm new to android so that's why i come to find help... Hi an introduction to the app i'm doing here, i'm actually doing an car blackbox app..
I had my service run the video recording processes in the background so i should be able to leave the app for a while and come back to the Video recording GUI with the surfaceview but my application was force to close when i return to the app. So is the problem related to onResume() method or something else? If its yes what i should do in order to get my application GUI to return to the video recording surfaceview and still running the background recording using the service rather than giving me an error? Can someone help please...
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;
}
}

[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??

Simple MediaPlayer project, problems WP7

I'm trying to create simple mediaplayer and using MediaPlayer Class, but I have some problems. When I select song from the list, my buttons Next and Prev stopped working. I try some things but nothing works, what I have to do, to fix this problem. I don't know how to use EventHandler - MediaStateChanged, will see this in the code below. I want to add simple progress bar, but this class don't have current position event. I read some about DispatcherTimer, but ...
The code:
Code:
namespace MediaViewer
{
public partial class MainPage : PhoneApplicationPage
{
private App app;
int songIndexForDetails;
public MainPage()
{
InitializeComponent();
app = Application.Current as App;
List<CategoryDetailsViewModel> items = new List<CategoryDetailsViewModel>();
items.Add(app.MusicModel);
PivotControl.ItemsSource = items;
ProgressBar.Visibility = Visibility.Collapsed;
txtCurrentState.Text = MediaPlayer.State.ToString();
}
private void ItemsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBox list = (ListBox)sender;
int selectedCategoryIndex = list.SelectedIndex;
songIndexForDetails = list.SelectedIndex;
if (selectedCategoryIndex == -1)
return;
List<CategoryDetailsViewModel> model = PivotControl.ItemsSource as List<CategoryDetailsViewModel>;
if (model[PivotControl.SelectedIndex].IsAnyItemAvailable())
{
if (model[PivotControl.SelectedIndex].PrepareItemForPreview(selectedCategoryIndex))
{
if (model[PivotControl.SelectedIndex] is MusicCategoryModel)
{
MediaLibrary library = new MediaLibrary();
FrameworkDispatcher.Update();
MediaPlayer.Play(library.Songs[selectedCategoryIndex]);
ProgressBar.Visibility = Visibility.Visible;
txtCurrentState.Text = MediaPlayer.State.ToString();
}
}
else
MessageBox.Show("Warining!\n\nUnable to open selected file.\nMake sure that your device is disconnected from the computer.");
}
}
private void detailsButton_Click(object sender, RoutedEventArgs e)
{
if (songIndexForDetails == -1)
{
return;
}
NavigationService.Navigate(new Uri("/Pages/SongDetailsPage.xaml?SelectedItem=" + songIndexForDetails, UriKind.Relative));
}
private void pauseButton_Click(object sender, RoutedEventArgs e)
{
MediaPlayer.Pause();
ProgressBar.Visibility = Visibility.Collapsed;
txtCurrentState.Text = MediaPlayer.State.ToString();
}
private void stopButton_Click(object sender, RoutedEventArgs e)
{
MediaPlayer.Stop();
ProgressBar.Visibility = Visibility.Collapsed;
txtCurrentState.Text = MediaPlayer.State.ToString();
}
private void playButton_Click(object sender, RoutedEventArgs e)
{
MediaLibrary library = new MediaLibrary();
FrameworkDispatcher.Update();
if (MediaPlayer.State == MediaState.Paused)
{
MediaPlayer.Resume();
}
else
{
MediaPlayer.Play(library.Songs);
ProgressBar.Visibility = Visibility.Visible;
txtCurrentState.Text = MediaPlayer.State.ToString();
}
}
private void nextButton_Click(object sender, RoutedEventArgs e)
{
MediaPlayer.MoveNext();
}
private void previousButton_Click(object sender, RoutedEventArgs e)
{
MediaPlayer.MovePrevious();
}
public Song GetModelForIndex(int itemIndex)
{
if (itemIndex < Songs.Count)
return Songs[itemIndex];
else
return null;
}
private List<Song> Songs { get; set; }
}
}

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;

Categories

Resources