how to write array into android file in the internal storage - java

I'm newbie at developing android application, so I am making this simple application to save a list of data that user input and able to read it as a list later on. I am able to write user input into a file, but every i input another list, it overwrite the first one, what I want is to add this in the file, and call the list as array to be displayed as a list. How do I write an array or achieve this ? Here's the code :
package com.example.storage;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText et;
private EditText st;
private String data;
private String file;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText)(findViewById(R.id.editText1));
st = (EditText)(findViewById(R.id.showText1));
}
public void save(View view) {
data = et.getText().toString();
file = st.getText().toString();
try {
FileOutputStream fOut = openFileOutput(file,MODE_WORLD_READABLE);
fOut.write(data.getBytes());
fOut.close();
Toast.makeText(getBaseContext(), "file saved",
Toast.LENGTH_SHORT).show();
} catch (Exception e){
//TODO Auto-generated catch block
e.printStackTrace();
}
}
public void read(View view) {
file = st.getText().toString();
try {
FileInputStream fin = openFileInput(file);
int c;
String temp = "";
while( (c = fin.read()) != -1) {
temp = temp + Character.toString((char)c);
}
et.setText(temp);
Toast.makeText(getBaseContext(),"file read",
Toast.LENGTH_SHORT).show();
} catch(Exception e) {
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Any help greatly appreciated. Thank you in advance.

what about using FileWriter(File file, boolean append) in "append" mode? Have a look here: How to append to a text file in android?
Try it like that:
File f = new File(pathToUrFile);
FileWriter fw = new FileWriter(file, true);
fw.append();
If you are going to save more (and different) values give gson a try to save and load vars or even classes from text files.
Best regards!

Related

Issue with Http Client in android studio

I am new to android app development, and one of my clients asked me to fix this code his past dev left the job . there were a lot of errors I was able to fix it. But now I am stuck at a point in HTTP request error in java and cannot execute this code. Let me know how to fix it. Current status complied SDK 33 and cannot downgrade the same. Code below. HTTP client is deprecated.
package com.ecom.ecommerce;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.TextView;
public class ActivityCategoryList extends Activity {
GridView listCategory;
ProgressBar prgLoading;
TextView txtAlert;
// declare adapter object to create custom category list
AdapterCategoryList cla;
// create arraylist variables to store data from server
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> Category_name = new ArrayList<String>();
static ArrayList<String> Category_image = new ArrayList<String>();
String CategoryAPI;
int IOConnect = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_list);
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new
ColorDrawable(getResources().getColor(R.color.header)));
bar.setDisplayHomeAsUpEnabled(true);
bar.setHomeButtonEnabled(true);
bar.setTitle("Category");
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
listCategory = (GridView) findViewById(R.id.listCategory);
txtAlert = (TextView) findViewById(R.id.txtAlert);
cla = new AdapterCategoryList(ActivityCategoryList.this);
// category API url
CategoryAPI = Constant.CategoryAPI+"?accesskey="+Constant.AccessKey;
// call asynctask class to request data from server
new getDataTask().execute();
// event listener to handle list when clicked
listCategory.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
// go to menu page
Intent iMenuList = new Intent(ActivityCategoryList.this, ActivityMenuList.class);
iMenuList.putExtra("category_id", Category_ID.get(position));
iMenuList.putExtra("category_name", Category_name.get(position));
startActivity(iMenuList);
overridePendingTransition(R.anim.open_next, R.anim.close_next);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_category, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.cart:
// refresh action
Intent iMyOrder = new Intent(ActivityCategoryList.this, ActivityCart.class);
startActivity(iMyOrder);
overridePendingTransition (R.anim.open_next, R.anim.close_next);
return true;
case R.id.refresh:
IOConnect = 0;
listCategory.invalidateViews();
clearData();
new getDataTask().execute();
return true;
case android.R.id.home:
// app icon in action bar clicked; go home
this.finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// clear arraylist variables before used
void clearData(){
Category_ID.clear();
Category_name.clear();
Category_image.clear();
}
// asynctask class to handle parsing json in background
public class getDataTask extends AsyncTask<Void, Void, Void>{
// show progressbar first
getDataTask(){
if(!prgLoading.isShown()){
prgLoading.setVisibility(0);
txtAlert.setVisibility(8);
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// when finish parsing, hide progressbar
prgLoading.setVisibility(8);
// if internet connection and data available show data on list
// otherwise, show alert text
if((Category_ID.size() > 0) && (IOConnect == 0)){
listCategory.setVisibility(0);
listCategory.setAdapter(cla);
}else{
txtAlert.setVisibility(0);
}
}
}
// method to parse json data from server
public void parseJSONData(){
clearData();
try {
// request data from Category API
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(CategoryAPI);
HttpResponse response = client.execute(request);
InputStream atomInputStream = response.getEntity().getContent();
BufferedReader in = new BufferedReader(new InputStreamReader(atomInputStream));
String line;
String str = "";
while ((line = in.readLine()) != null){
str += line;
}
// parse json data and store into arraylist variables
JSONObject json = new JSONObject(str);
JSONArray data = json.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
JSONObject object = data.getJSONObject(i);
JSONObject category = object.getJSONObject("Category");
Category_ID.add(Long.parseLong(category.getString("Category_ID")));
Category_name.add(category.getString("Category_name"));
Category_image.add(category.getString("Category_image"));
Log.d("Category name", Category_name.get(i));
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
//cla.imageLoader.clearCache();
listCategory.setAdapter(null);
super.onDestroy();
}
#Override
public void onConfigurationChanged(final Configuration newConfig)
{
// Ignore orientation change to keep activity from restarting
super.onConfigurationChanged(newConfig);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
}
}

How can I get my app to read external text file correctly? Only showing weird characters and diamonds

I'm working on my first app. Got everything set up and working correctly, except displaying a random quote from a text file. Clicking the button shows weird characters (diamonds, question marks, etc) and not the actual text except for the placeholder off and on.
I followed the github source correctly as far as I know.
package drewstephensdesigns.com.dailyquotes;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ShareActionProvider;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
private TextView mTextView;
private String STATE_DQ;
private static String TEXT_VALUE = "";
private ShareActionProvider mShareActionProvider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.dq_view);
//Adds scrolling to the TextView
mTextView.setMovementMethod(ScrollingMovementMethod.getInstance());
}
//Code to save state on orientation change
#Override
public void onSaveInstanceState(Bundle outState) {
mTextView = (TextView) findViewById(R.id.dq_view);
outState.putString(STATE_DQ, mTextView.getText().toString());
super.onSaveInstanceState(outState);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mTextView = (TextView) findViewById(R.id.dq_view);
mTextView.setText(STATE_DQ);
}
private AssetManager getApplicationAssets() {
// open random quotes file
AssetManager assetmanager = getAssets();
return assetmanager;
}
private String getAssetPath(AssetManager assetmanager) {
String[] dirs = null;
String[] files = null;
String path = null;
try {
dirs = assetmanager.list(""); //get list of files / dirs from the project 'assets' directory
files = assetmanager.list(dirs[2]); //Directories are listed in alphabetical order so fetch the 'txt' directory
path = dirs[2].toString() + "/" + files[0].toString(); //construct the path (there is only 1 file in the dir)
} catch (IOException e) {
e.printStackTrace();
}
return path;
}
// Get the path for the random quote file
private InputStreamReader getQuoteReader() throws IOException {
// open random quotes file
AssetManager assets = getApplicationAssets();
String path = null;
path = getAssetPath(assets);
InputStream inputStream = null;
try {
inputStream = assets.open(path);
Log.v("QotD path", path);
} catch (IOException e) {
e.printStackTrace();
}
InputStreamReader textReader = new InputStreamReader(inputStream);
return textReader;
}
// Get the total number of lines in the file
private int getFileLineCount(InputStreamReader textReader) {
BufferedReader br = new BufferedReader(textReader);
int lineCount = 0;
try {
while ((br.readLine()) != null) {
lineCount++;
}
} catch (IOException e) {
e.printStackTrace();
}
return lineCount; // total number of lines in the text file
}
// Return a random line number from where to get the
// corresponding quote string
private int getRandomLineNumber(int totalLines) {
Random rand = new Random();
return rand.nextInt(totalLines);
}
private String getRandomQuote(int lineToFetch)
throws IOException {
//1. get path
AssetManager assets = getApplicationAssets();
String path = null;
path = getAssetPath(assets);
//2. open assets
InputStream stream = assets.open(path);
InputStreamReader randomQuote = new InputStreamReader(stream);
//3. Get BufferedReader object
BufferedReader buf = new BufferedReader(randomQuote);
String quote = null;
String line = null;
int currLine = 0;
//4. Loop through using the new InputStreamReader until a match is found
while ((line = buf.readLine()) != null && currLine < lineToFetch) {
currLine++;
}
//Got the quote
quote = line;
//Clean up
randomQuote.close();
buf.close();
return quote;
}
// Set the EditText widget to display the new random quote
private void displayQuote(String quote) {
TextView quoteDisplay = (TextView) findViewById(R.id.dq_view);
TEXT_VALUE = quote;
quoteDisplay.setText(TEXT_VALUE);
}
// onClick handler for the button click
public void fetch_quote(View view) throws IOException {
// open random quotes file
InputStreamReader textReader = getQuoteReader();
final int totalLines = getFileLineCount(textReader);
int lineToFetch = 0;
String quote = null;
// We want to get the quote at the following line number
lineToFetch = getRandomLineNumber(totalLines);
quote = getRandomQuote(lineToFetch);
displayQuote(quote);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem shareItem = menu.findItem(R.id.menu_item_share);
mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(shareItem);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
switch(item.getItemId()){
case R.id.menu_item_share:
if(TEXT_VALUE == "") {
Toast.makeText(this, "Nothing to share! First generate a quote by clicking the button", Toast.LENGTH_SHORT).show();
} else {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, TEXT_VALUE);
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Thought you might like this interesting Quote");
startActivity(Intent.createChooser(shareIntent, "Share the quote via..."));
}
break;
case R.id.action_settings:
Toast.makeText(getApplicationContext(), "Settings not yet implemented", Toast.LENGTH_LONG).show();
break;
case R.id.action_about:
Intent aboutIntent = new Intent(this, AboutActivity.class);
startActivity(aboutIntent);
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
}
This is what I see:
I had a folder called "fonts" that was not being used. My code was looking for the assets folder with just the randomquote.txt file. Due to the extra folder in there, it was unable to locate the txt file. Deleted the folder since it wasn't being used, saved, boom and progress.

ArrayIndexOufofBoundExceptin in zipping file by android programming

I am newbie in android programming, Currently i am trying to do zipping multiple files in android. in my SD card a zipfile is created but it has no files inside and 0.00 byte showing . In logcat i have got some exception like
java.lang.ArrayIndexOutOfBoundsException: length=2040; regionStart=0; regionLength=-1
at java.util.Arrays.checkOffsetAndCount(Arrays.java:1732)
Here is my code
package com.example.zipfile;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import android.util.Log;
public class CompressFile
{
public static final int Buffer=2040;
public String[]localfiles;
public String zippedFile;
public CompressFile(String[]localfileset,String zipFileset)
{
// TODO Auto-generated constructor stub
this.localfiles=localfileset;
this.zippedFile= zipFileset;
}
public void zip()
{
try
{
BufferedInputStream bufferstream=null;
FileOutputStream fileout=new FileOutputStream(zippedFile);
ZipOutputStream zipout=new ZipOutputStream(new BufferedOutputStream(fileout));
byte[]data=new byte[Buffer];
for(int i=0;i<localfiles.length;i++)
{
Log.d("add",localfiles[i]);
Log.v("Compress","AddingFiles:"+ localfiles[i]);
FileInputStream fileinput=new FileInputStream(localfiles[i]);
bufferstream=new BufferedInputStream(fileinput,Buffer);
ZipEntry zipentry=new ZipEntry(localfiles[i].substring(localfiles[i].lastIndexOf("/")+1));
zipout.putNextEntry(zipentry);
int count;
while((count=bufferstream.read(data,0,Buffer))!=-1);
{
zipout.write(data,0,count);
}
bufferstream.close();
}
zipout.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
and my MainActvity code
package com.example.zipfile;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[]filelist=new String[2];
String path=Environment.getExternalStorageDirectory().getPath();
filelist[0]=path+"/facebooklogo1.png";
filelist[1]=path+"/formpicture.jpg";
CompressFile compress=new CompressFile(filelist,path+"/Testzip.zip");
compress.zip();
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
i am not getting why it is happening , A help is appreciated
Thanks in advance
1) Check file path
2) localfiles[i].substring(localfiles[i].lastIndexOf("/")+1) this should be unique entry for Zip file.
`
byte[] data = new byte[4096];
// Read bytes from packed file and store them in the ZIP output stream
int bytesNum;
while ((bytesNum = bufferstream.read(data)) > 0) {
zipout.write(data, 0, bytesNum);
}
`
i have re modified my code i didn't buffredInputStream this time thanks rahul for your suggestion . Here is my code its working
package com.example.ziptest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
String path= Environment.getExternalStorageDirectory().getPath();// stating relative path of SD card rather than hard coded path
String zipfile=path+File.separator+"Filekb.zip"; // the new compressed file with its path
String storagefile1=path+File.separator+"facebooklogo1.png"; // local file which is going to be compressed
String storagefile2=path+File.separator+"formpicture.jpg"; // second local file which is going to be compressed
String[]storagefiles= {storagefile1,storagefile2};// put this local files in a array
public byte[]buffer=new byte[2040]; // create buffer
FileInputStream fileinput;
FileOutputStream fileoutput;
ZipOutputStream zipout;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
zip();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void zip()
{
try
{
fileoutput=new FileOutputStream(zipfile);
zipout =new ZipOutputStream(fileoutput);
for(int i=0;i<storagefiles.length;i++)
{
File storagefileindex=new File(storagefiles[i]);
Log.d("Add", storagefiles[i]);
Log.v("compressing","Adding"+storagefiles[i]);
fileinput=new FileInputStream(storagefileindex);
zipout.putNextEntry(new ZipEntry(storagefileindex.getName()));
int bytecount;
while((bytecount= fileinput.read(buffer))>0)
{
zipout.write(buffer,0,bytecount);
}
zipout.closeEntry();
fileinput.close();
}
zipout.close();
}
catch(Exception ioe)
{
Log.d(zipfile, "Error occurs in Creating zip");
}
}
}

Trying to get a simple Camera application to work

I'm a beginner to Android app development. I'm getting the hang of it, and I've read a lot of tutorials, but I still can't get the camera to work. Basically what I want to do is take a picture, store the image internally within the app and then display that image to (later) be able to draw on it. I'm not worried about the drawing part at the moment because I'm still getting an error for SetOnClickListener...Here's the code.
import android.hardware.Camera;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create an instance of Camera
Camera mCamera = getCameraInstance();
// Create our Preview view and set it as the content of our activity.
CameraPreview mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
}
private Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
// Log.d("erre", "Error creating media file, check storage permissions: " +
// getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d("erra", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("erra", "Error accessing file: " + e.getMessage());
}
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
// Add a listener to the Capture button
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Camera mCamera = getCameraInstance();
// get an image from the camera
mCamera.takePicture(null, null, mPicture);
}
}
);
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
}
Simply move this part:
// Add a listener to the Capture button
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Camera mCamera = getCameraInstance();
// get an image from the camera
mCamera.takePicture(null, null, mPicture);
}
}
);
into your onCreate() function, at the end of it. Then it should work.
You need to find views / setup click events in the onCreate of Activities.

How can I make this app more efficient?

I have the following code which is working without any errors, but I get this
Skipped 116 frames. The application may be doing too much work on its main thread.
That happens when I press the Single button and the init() method is executed.
How can I execute the method in another thread so it won't break like that ?
package com.apppppp.pampam;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.Set;
import android.support.v7.app.ActionBarActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.ParcelUuid;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
Button singleButton;
BluetoothAdapter mBluetoothAdapter;
BluetoothAdapter blueAdapter ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
blueAdapter = BluetoothAdapter.getDefaultAdapter();
singleButton = (Button) findViewById(R.id.button1);
setButtonOnClickListeners();
return true;
}
private void setButtonOnClickListeners(){
singleButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
try {
write("Salut");
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("No luck");
}
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private OutputStream outputStream;
private InputStream inStream;
private void init() throws IOException {
if (blueAdapter != null) {
if (blueAdapter.isEnabled()) {
Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();
System.out.println(bondedDevices);
if(bondedDevices.size() > 0){
Iterator iter = bondedDevices.iterator();
BluetoothDevice device = (BluetoothDevice) iter.next();
ParcelUuid[] uuids = device.getUuids();
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
socket.connect();
outputStream = socket.getOutputStream();
inStream = socket.getInputStream();
}
else{
Log.e("error", "No appropriate paired devices.");
}
}else{
Log.e("error", "Bluetooth is disabled.");
}
}
}
public void write(String s) throws IOException{
init();
outputStream.write(s.getBytes());
}
public void run() {
final int BUFFER_SIZE = 1024;
byte[] buffer = new byte[BUFFER_SIZE];
int bytes = 0;
int b = BUFFER_SIZE;
while (true) {
try {
bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Thank you
You are doing the Bluetooth related calls on the UI thread and you blocking the UI thread with these calls.

Categories