Save calculator result problem - myTouch 3G, Magic Android Development

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

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

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; }
}
}

Basic android animation code

Here is the code for a basic animation program in Android:
Code:
[SIZE="2"][FONT="Courier New"]import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import android.content.*;
import android.graphics.*;
import javax.xml.parsers.*;
import javax.security.cert.*;
public class MainActivity extends Activity
{
DrawView drawView = null;
@Override public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setTitle("Animation Example");
drawView = new DrawView(this);
setContentView(drawView);
}
@Override public void onPause()
{
super.onPause();
drawView.pause();
}
@Override public void onResume()
{
super.onResume();
drawView.resume();
}
}
class DrawView extends SurfaceView implements SurfaceHolder.Callback
{
DrawThread thread = null;
int screenWidth = 0;
int screenHeight = 0;
int radius = 40;
int boundaryTop = 0;
int boundaryBottom = 0;
int boundaryLeft = 0;
int boundaryRight = 0;
float ppsX = 0; // horizontal velocity in pixels per second
float ppsY = 0; // vertical "
float x = 0;
float y = 0;
long lastDrawTime = 0;
int minIntervalMs = 15; // limit frame rate
Paint paint = null;
public DrawView(Context context)
{
super(context);
paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.BLUE);
getHolder().addCallback(this);
setFocusable(true);
}
public void initialize(int screen_width, int screen_height)
{
screenWidth = screen_width;
screenHeight = screen_height;
x = screenWidth / 2.0f;
y = screenHeight / 2.0f;
boundaryTop = radius;
boundaryBottom = screenHeight - radius - 1;
boundaryLeft = radius;
boundaryRight = screenWidth - radius - 1;
ppsX = 250;
ppsY = 100;
}
public void startThread()
{
thread = new DrawThread(getHolder());
thread.setRunning(true);
thread.start();
}
public void stopThread()
{
boolean retry = true;
thread.setRunning(false);
while (retry)
{
try { thread.join(); retry = false; }
catch (InterruptedException e) { }
}
}
public void pause()
{
stopThread();
lastDrawTime = 0;
}
public void resume()
{
}
@Override public void surfaceCreated(SurfaceHolder holder)
{
startThread();
}
@Override public void surfaceDestroyed(SurfaceHolder holder)
{
stopThread();
}
@Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
{
}
@Override public void onSizeChanged(int width_new, int height_new, int width_old, int height_old)
{
super.onSizeChanged(width_new, height_new, width_old, height_old);
initialize(width_new, height_new);
}
@Override public synchronized boolean onTouchEvent(MotionEvent event)
{
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
{
break;
}
case MotionEvent.ACTION_UP:
{
break;
}
case MotionEvent.ACTION_MOVE:
{
break;
}
}
return true;
}
public void updateCanvas(Canvas canvas)
{
if (lastDrawTime != 0)
{
long intervalMs = System.currentTimeMillis() - lastDrawTime; // interval in milliseconds
if (intervalMs < minIntervalMs)
{
try { Thread.sleep(minIntervalMs - intervalMs); }
catch (InterruptedException e) { }
intervalMs = minIntervalMs;
}
float intervalS = intervalMs / 1000.0f; // interval in seconds
x = x + intervalS * ppsX;
if (x < boundaryLeft)
{
x = boundaryLeft;
ppsX = -ppsX;
}
else if (x > boundaryRight)
{
x = boundaryRight;
ppsX = -ppsX;
}
y = y + intervalS * ppsY;
if (y < boundaryTop)
{
y = boundaryTop;
ppsY = -ppsY;
}
else if (y > boundaryBottom)
{
y = boundaryBottom;
ppsY = - ppsY;
}
}
canvas.drawColor(Color.WHITE);
canvas.drawCircle(x, y, radius, paint);
lastDrawTime = System.currentTimeMillis();
}
class DrawThread extends Thread
{
private SurfaceHolder holder = null;
private boolean run = false;
public DrawThread(SurfaceHolder holder)
{
this.holder = holder;
}
public void setRunning(boolean run)
{
this.run = run;
}
@Override public void run()
{
Canvas canvas = null;
while (run)
{
canvas = null;
try
{
canvas = holder.lockCanvas(null);
synchronized (holder)
{
updateCanvas(canvas);
}
}
finally
{
if (canvas != null)
{
holder.unlockCanvasAndPost(canvas);
}
}
}
}
}
}
[/FONT][/SIZE]

Unable to display images in webView while epub Rendering using epublib.

Here is the code of my epub parser class.
public class EPubParser extends AppCompatActivity {
String path = null;
Book book = null;
String linez = null;
TextView textView;
private int pxScreenWidth;
int textSize = 12;
Drawable imageAsDrawable;
List<String> spineElements;
List<SpineReference> spineList;
@SuppressLint("SetJavaScriptEnabled")
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.layout_epub_render);
getSupportActionBar().setTitle("EPub Reader");
WebView webView = (WebView) findViewById(R.id.web_view);
webView.setWebChromeClient(new WebChromeClient());
webView.getSettings().setJavaScriptEnabled(true);
//to get Path
Intent intent = this.getIntent();
if (intent.getAction() != null) {
path = intent.getData().getPath();
} else {
path = intent.getExtras().getString("PATH");
}
try {
File file = new File(path);
FileInputStream fileInputStream = new FileInputStream(file);
EpubReader epubReader = new EpubReader();
book = epubReader.readEpub(fileInputStream);
} catch (Exception e) {
Log.e("While loading book ", e.toString());
}
//loading the contents
Spine spine = book.getSpine();
spineList = spine.getSpineReferences();
int count = spineList.size();
//gathering all data from spine
StringBuilder string = new StringBuilder();
for (int i = 0; i < count; i++) {
Resource res = spine.getResource(i);
try {
InputStream is = res.getInputStream();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
String line = null;
try {
while ((line = reader.readLine()) != null) {
linez = string.append(line + "\n").toString();
}
} catch (IOException e) {
e.printStackTrace();
}
//do with stream
} catch (IOException e) {
e.printStackTrace();
}
// linez = linez.replace("../", "");
webView.loadDataWithBaseURL(null, linez, "text/html", "UTF-8", null);
webView.getSettings().setBuiltInZoomControls(true);
}
}
}
Please help.

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