I'm new to java, but a quick learner.
I'm trying make my Android App to take user-input from an EditText, search an Excel column for a matching string, and return the value of (the same row of) another column.
I added a jxl.jar on the build path, and my code seems like it should work. Teaching myself, I am slowly figuring out the debugging. The problem seems to be source android.jar was not found (if i remember correctly). I located it, and now I get "the source attachment does not contain the source for the file instrumentation.class"
This is my first app using excel. Do I need to address the Android Manifest somehow?
Here's my code, just in case, and any help is very appreciated!:
public class Frame_Bore extends Activity {
private String inputFile;
public void setInputFile(String inputFile) {
this.inputFile = "c:/Desktop/AAS Work/PDA Programs/JBDB.xls";
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.framebore);
Button Btn1 = (Button) findViewById(R.id.button1);
final EditText T1 = (EditText) findViewById(R.id.et1);
final EditText T2 = (EditText) findViewById(R.id.et2);
Btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String t1Value = T1.getText().toString();
File inputWorkbook = new File(inputFile);
Workbook w;
String bore = null;
try {
w = Workbook.getWorkbook(inputWorkbook);
Sheet sheet = w.getSheet("Frame-Bore");
int y = 6;
while (y < 200) {
int x = 2;
Cell columnB = sheet.getCell(x, y);
String motorframe = columnB.getContents();
if (motorframe == t1Value) {
Cell columnC = sheet.getCell(x + 1, y);
bore = columnC.getContents();
} else {
y = y + 1;
}
}
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
T2.setText("" + bore);
}
}
});
}
You are trying to access c: drive ( "c:/Desktop/AAS Work/PDA Programs/JBDB.xls" ) from your emulator, which is not possible. You need to put your excel file either in the resources folder or in SD card, if you are running it in device.
An Emulator has a virtual SD Card, and its limitations is that it can not direct access any other drive from the computer. However you can do it by making a webservice which will perform operation on behalf of your android application. You need to call this web-service from your android application.
Put the file in assets folder and access it like this:
InputStream is = null;
try {
is = context.getAssets().open("JBDB.xls");
workbook = Workbook.getWorkbook(is);
} catch (IOException e) {
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
}
if(workbook!=null)
sheet = workbook.getSheet("Frame-bore");
context is your main activity context.
Related
I am trying desperately to read a file from Android Studio asset folder. The file is "ok.txt" and contains the string: yo chicken mcgriddle fiddle fiddle.
Per this video: https://youtu.be/1CHDASXojNQ and stackoverflow browsing, this is the solution I came up with:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
tv_text = (TextView) findViewById(R.id.nameView);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
tv_text.setText(LoadData("ok.txt"));
}
public String LoadData(String inFile) {
String tContents = "";
try {
InputStream stream = getAssets().open(inFile);
int size = stream.available();
byte[] buffer = new byte[size];
stream.read(buffer);
stream.close();
tContents = new String(buffer);
} catch (IOException e) {
// Handle exceptions here
}
return tContents;
}
});
}
}
I am inclined to believe that the code works, but, it does not return the String. In the app, it returns a blank message in the place of the textview's "hello world" placeholder after clicking the button. I thought it was due to the limitation of the textview so I modified the constraint size, but the blank persists. Anybody know what's up?
I have attempted to create an App that plays wavfiles that have been created from another app I have made that records wavFiles.
The wav files I would like to play are stored in the following directory with my android device.
"/data/data/com.example.androidaudiorecorder/files/"
Here is the code I have attempted so far :
public class MainActivity extends AppCompatActivity {
Button playEvent ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playEvent= (Button) findViewById(R.id.btnPlayEvent);
playEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
playEvent( );
}
});
}
public static void playEvent(){
try {
MediaPlayer player = new MediaPlayer();
player = new MediaPlayer();
player.setDataSource("/data/data/com.example.androidaudiorecorder/files/recording_DOG.wav");
player.prepare();
player.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (Exception e) {
System.out.println("Exception of type : " + e.toString());
e.printStackTrace();
}
}
}
}
Unfortunatley when I load the app and press play, nothing happens.
I am not sure if this is the correct way to use a file directory.
Any advice on how to fix this would be greatly appreciated.
1) You need to give permissions in the android manifest file to access storage before reading/writing any content int the storage .
2) To read the file,
File dir = Environment.getExternalStorageDirectory();
File yourFile = new File(dir, "path/filename.extension");
The Code I am using .
I am print the error code on textview.This is given the ERROR_NOT_MATCH ADDRESS. I am using the this by some links and with brother Sdk.
The Links I am using this By Link using
public class printerApp extends Activity {
TextView mytext;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mytext=(TextView)findViewById(R.id.mytext);
printTemplateSample();
}
public void printTemplateSample() {
Printer myPrinter = new Printer();
PrinterInfo myPrinterInfo = new PrinterInfo();
PrinterStatus printResult = new PrinterStatus();
LabelInfo mLabelInfo=new LabelInfo();
try{
myPrinterInfo = myPrinter.getPrinterInfo();
myPrinterInfo.ipAddress="192.168.0.122";
myPrinterInfo.macAddress="00:80:92:d7:f4:0d";
myPrinterInfo.printerModel= PrinterInfo.Model.QL_720NW;
myPrinterInfo.printMode= PrinterInfo.PrintMode.FIT_TO_PAGE;
myPrinterInfo.port= PrinterInfo.Port.NET;
myPrinterInfo.paperPosition= PrinterInfo.Align.CENTER;
myPrinterInfo.paperSize = PrinterInfo.PaperSize.CUSTOM;
myPrinterInfo.orientation = PrinterInfo.Orientation.PORTRAIT;
myPrinterInfo.halftone = PrinterInfo.Halftone.PATTERNDITHER;
myPrinterInfo.align = PrinterInfo.Align.LEFT;
myPrinterInfo.margin.left = 0;
myPrinterInfo.valign = PrinterInfo.VAlign.TOP;
myPrinterInfo.customPaperLength = 0;
myPrinterInfo.customPaperWidth = 0;
myPrinterInfo.customFeed = 0;
myPrinterInfo.paperPosition = PrinterInfo.Align.CENTER;
myPrinterInfo.dashLine = false;
// myPrinterInfo.isSpecialTape=
myPrinterInfo.numberOfCopies = 1;
myPrinterInfo.labelNameIndex= 15;
myPrinterInfo.isAutoCut = false;
myPrinterInfo.isCutAtEnd =false;
// myPrinter.setLabelInfo(mLabelInfo);
myPrinter.setPrinterInfo(myPrinterInfo);
//myPrinter.setPrinterInfo(myPrinterInfo);
// Create bitmap
Bitmap bmap = BitmapFactory.decodeResource(getResources(), R.mipmap.dcs);
try {
mytext.append("Start" + "\n");
myPrinter.startCommunication();
PrinterStatus printerStatus = myPrinter.printImage(bmap);
myPrinter.endCommunication();
mytext.append(printerStatus.errorCode.toString() + "\n");
} catch (Exception e) {
mytext.setText(e.toString());
}
} catch (Exception e) {
mytext.setText(e.toString());
//e.printStackTrace();
}
}
}
I am print an image from resources folder also I am trying this to print the text also. but every time I am getting this error which is showing above
thanks in advance to all viewers please help me.....
I solved this By integrate The Sdk demo in my Code... Sdk download with sample demo
for all brother printer
I set the all preference in my code which printer need.
I'm creating a text file with timestamps derived from the result of System.currentTimeMillis(). My algorithm is such:
Create file and record timestamp of creation
Save timestamp each time a button is pressed
Subtract file-creation timestamp from button-press timestamp
Write result to the file
For some odd reason, the timestamp of the file creation is usually greater (younger, more recent) than the timestamp of the button presses, which always happen AFTER the file was created. This results in a negative value being returned from step 3.
What is causing this?
FileCreationMenu.java
public class FileCreationMenu extends Fragment {
public Button toggleRecordingButton;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.menu_fragment_calibrator, container, false);
toggleRecordingButton = (Button) v.findViewById(R.id.recordAudioToggle);
toggleRecordingButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
recordAudio = !recordAudio; //toggle audio recording on/off
if (recordAudio==true){
AudioRecorder.createFile(System.currentTimeMillis()); //generate file for new track if record is togged ON
}
}
});
AudioRecorder.java
public static void createFile(long time) { //create file and record creation timeStamp
recordingStartTime = time;
myFile = new File(Environment.getExternalStorageDirectory(), "file.txt"); //save to external storage
try {
myFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void recordNote(long timeStamp){ //record timeStamps of notes
String playedNote = (timeStamp+ "\n" );
try {
fos = new FileOutputStream(myFile, true);
fos.write(playedNote.getBytes());
fos.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void playTrack(String fileName){ //playback Notes
try {
FileInputStream fis = new FileInputStream(myFile.getPath());
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line;
try {
int i =0;
while ((line = reader.readLine()) != null) { //read each line of input file
historicalTime[i] = Long.parseLong(line); //store time current line's note was played
if (i==0){
timeStream[i] = (Long.parseLong(line) - recordingStartTime); //if first note, calculate wait based on file creation time
}
else{
timeStream[i] = (Long.parseLong(line) - historicalTime[i-1]); //otherwise, calculate wait as amount of time note was played after most recent preceding note
}
i++;
}
} catch (IOException e){
e.printStackTrace();
}
for (int i=0; i<noteStream.length; i++){
try {
AudioRecorder.class.wait(timeStream[i]); //wait
//Play Note
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
MainActivity.java
...
public static void noteDetected(){
if (FileCreationMenu.recordAudio == true){
AudioRecorder.recordNote(System.currentTimeMillis());
}
Again, the problem is that recordingStartTime in AudioRecorder.java is often greater than the input parameter "timeStamp" to recordNote from the MainActivity. For example, in a recent debugging session recordingStartTime =1,450,573,093,044 while timeStamp=1,450,565,187,318.
What could be causing this seemingly impossible behavior?
The problem is this line:
myFile.createNewFile();
The JavaDoc for this method says
Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist
So every time you try to start a new recording you are actually reusing the same file (with timestamps from long ago) but record a new recordStartTime.
If you want to remove the old file first you will have to write
myFile.delete();
myFile.createNewFile();
Fairly new to android, I come from a heavy fortran background. I've been trying to make apps, sucessful until now.
I'm having trouble finding a way for: saving an 'edittext' field by use of a button(save), then saving this user inputted data to a .csv file(preferably in internal storage).
I've found many articles but everyone glazes over the fundemental part I want(above).
the best idea I've got, is of generating the .csv in the class, then creating a method to save the 'edittext' as a new string, then to output that string to the .csv
Hopefully this can be simply explained, I just cant find this simple explanation anywhere, or at-least that I can understand...
Please try this.I hope this code helps you.
CSVFileWriter.java
public class CSVFileWriter {
private PrintWriter csvWriter;
private File file;
public CSVFileWriter(File file) {
this.file = file;
}
public void writeHeader(String data) {
try {
if (data != null) {
csvWriter = new PrintWriter(new FileWriter(file, true));
csvWriter.print(",");
csvWriter.print(data);
csvWriter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
SampleActivity.java
public class SampleActivity extends Activity {
CSVFileWriter csv;
StringBuffer filePath;
File file;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
saveButton = (Button) findViewById(R.id.button1);
editText = (EditText) findViewById(R.id.editText1);
filePath = new StringBuffer();
filePath.append("/sdcard/abc.csv");
file = new File(filePath.toString());
csv = new CSVFileWriter(file);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
csv.writeHeader(editText.getText().toString());
}
});
}
}
Add this in manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />