How to compile Java Code got from editText in android studio - java

I wanna develop apps that can compile a java code from editText. So the user write code in editText and if i click the button, programm will compile the text from edit text and show the result in textView. i found the app similar i mean such as AIDE. is there anyone can help me solution to build apps like this?

How about saving user's code somewhere in the device as .java file and then running shell command for compiling file and processing user's code.
refere below code
try{
Process su = Runtime.getRuntime().exec("su");
DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());
outputStream.writeBytes("screenrecord --time-limit 10 /sdcard/MyVideo.mp4\n");
outputStream.flush();
outputStream.writeBytes("exit\n");
outputStream.flush();
su.waitFor();
}catch(IOException e){
throw new Exception(e);
}catch(InterruptedException e){
throw new Exception(e);
}
Not providing required shell commands for the purpose as they would vary language to language but easy to explore.
Other option could be to call some online service that can do the compilation and provide the result.

Related

When reading an external PDF with an Android App it always shows the same version, even after updating the PDF

Please donĀ“t be too harsh to me concerning any mistakes with this question since thats my first one here.
So basically what i want to do is reading/showing a PDF document in my Android App after pressing a button. The PDF is located on a Raspberry Pi 3 and i found a code example on this thread how to read it.
Before accessing it however, i call a python script on the Raspi which is (re)creating the PDF based on a database.
So the user presses the button in the App and sees a PDF which presents the current state of a database table.
Now i got the following code in my Activity to call the script and read the PDF:
new AsyncTask<Integer, Void, Void>(){
#Override
protected Void doInBackground(Integer... params) {
try {
executeRemoteCommand("user","pw","ip", port, "command to execute the python script");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}.execute(1);
//waiting for the PDF to be created
handler.postDelayed(new Runnable() {
#Override
public void run() {
String url = "http://IP/path/file.pdf";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
}, 5000);
With this code connecting to the Raspberry, executing the python script, thus updating the database and reading the PDF file works just fine.
But i have the following problem:
When i close the PDF view in my App, add something to the database and press the executing button again the PDF file itself is being updated (i checked that on the Raspberry) but then the App still shows the old version of it. Even when i restart the App and execute this again it still shows the first version of the PDF...
Does anyone have an idea why and how to fix this?
Is there any kind of cache which stores the PDF and just shows the same every time i read from the Raspberry?

Bring control from application to java frame

I use a java program for communication between a arduino board and a scratch file. The communication happen well. I use a user interface to start the communication where i have buttons called
connect
close and minimize
When the user clicks the connect button code will check the value in combo box and accordingly it opens the scratch file.
Once the connect button is clicked the control moves to the scratch application. After completing my work when i tried closing the scratch. My scratch application closes as expected but the control does not return to the user interface because of which i am not able to close the application and i close it in net beans forcefully. In the output screen i don't see build successful and instead i get build stopped. That is my process works perfectly until i give connect but once the button is pressed it is hanged up some where.
I tried making it as a jar file and running it in a different machine at that time i use end task in task manager to close the application.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if("Disconnect".equals(jButton1.getText()))
{
System.exit(0);
}
if(jComboBox2.getSelectedItem()==null)
{
System.out.println("Select one port");
}
else
{
Runtime r = Runtime.getRuntime();
try {
//this.hide();
//p = r.exec("C:\\Program Files\\Scratch 2\\Scratch 2.exe C:\\Users\\Admin\\Desktop\\fwdbckpwm12.sb2");
p = Runtime.getRuntime().exec("C:\\Program Files\\Scratch 2\\Scratch 2.exe C:\\Users\\Admin\\Desktop\\scratch files new.sb2");
//Runtime.getRuntime().exec("taskkill /F /IM <p>.exe");
//p.destroy();
//r.exec("C:\\Windows\\notepad.exe C:\\Windows\\ss.txt");
//this.setDefaultCloseOperation(EXIT_ON_CLOSE);
A4S a4sObj = new A4S(new String[] {jComboBox2.getSelectedItem().toString()}); //defaultline
//A4S a4sObj = new A4S(new String[]{"COM16"}); //addedline
//r.gc();
//this.setDefaultCloseOperation(EXIT_ON_CLOSE);
} catch (IOException ex) {
Logger.getLogger(serialportselection.class.getName()).log(Level.SEVERE, null, ex);
}
finally{
//p.destroy();
//System.gc();
// }
}
Here is the code i tried. But none seems to work.
Move all Process related work into separate Thread.
Use waitFor method to recognise Process end - then you are free to
exit your app.
As I can understood you used SWING for creating UI.
You can set
yourFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
for your frame. This must help.

How to close a windows explorer?

I have a code that uses jDesktop to open a windows explorer interface when I clicked the button LOGIN and it's working right..
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Desktop desktop = Desktop.getDesktop();
File dirToOpen;
try {
dirToOpen = new File("C://as//2010-0000-1");
desktop.open(dirToOpen);
} catch (IOException ex) {
ex.getMessage();
} catch (IllegalArgumentException iae) {
System.out.println("File Not Found");
}
}
then now, my problem is when I click the button LOGOUT, the jDesktop windows explorer interface should also be closed... I dont know what codes to use....
This is not so simple, they only chance you have is if you have a reference to the process in question. This is going to mean you're going to need to take more control over the process...This also means that it will only work on Windows...
I use the following code to show a specified file in Windows Explorer...
String path = file.getCanonicalPath();
ProcessBuilder pb = new ProcessBuilder("explorer.exe", "/select," + path);
pb.redirectError();
Process proc = pb.start();
Once you have access to the Process, you can try using Process#destory to try and terminate the process.
Launching the process should be done from a separate thread, so you don't get yourself all tied up in a block point, you should also consume the Process's output just incase it causes the process to stall.
ps- I don't have access to a Windows machine at the moment, so I'm not sure if Process#destory will work ;)

Create a folder, create file, print logcat, send email

Im still very new to Android development, so I apologize in advance if my question seems silly.
In my application I have one button. When the button is clicked it attempts to see if the application has its own folder on the internal storage, if not it creates a folder, then it creates a file called output.txt, then it writes system information to the output.txt, then it attempts to write all lines containing "SIP_MESSAGE" from the logcat into the output.txt, it then emails the default email address.
EDIT
After a few days of toiling I managed to put it all together. Please read the answer below for everything in detail.
After a few days of research and a countless number of guess and checks, I finally figured everything out. I want to take this time to actually explain everything, in case anyone comes across this and is having the same problems that I had. Hopefully everything you are looking for is right here, and I gave a better explanation then the 100's of other sites that you (and I) had visited previous to this.
First topic is the difference between internal and external storage (it's not the difference between sdcard and not sdcard).
Internal storage is something that no one can see or get to but your application. If you create a file or folder on the internal storage, you cant use a file browser (unless your rooted) or your computer to see what you've created, it is completely inaccessible from outside your application.
Public folders such as Documents/Downloads/Music/Ringtones/etc. are technically on you external storage. You need permissions to write and read from it. This is where I was getting confused. I thought only sdcards counted as external storage, external storage is something you can manually get to from a computer or file browser whether its on an sdcard or not.
To create a file on the internal or external storage you do not need to use mkDir(). Anyone that says you do, is overly complicating things. You can actually create any text file anywhere on the system just from the code:
PrintWriter osw = new PrintWriter(Environment.getExternalStoragePublicDirectory(DOWNLOAD_SERVICE).toString() + "/output.txt");
This creates a text file in the download directory, whether it existed there or not first. You can also use getDataDirectory() or wherever else you want to create the file.
Next Logcat, like what the other people were pointing out, I was trying to read from the logcat as it was being created. There is no end to the logcat, so in effect, my application hung because it was constantly looking for more to write. An easy way around this is to use the -d feature of logcat. What that does is it just takes everything up to the point where -d was entered (which was exactly what I wanted), then it stops, then you can put it into a buffer and get the output with no hanging.
Finally, attaching a file to an email intent. This one was tricky because there were a few different areas that ended up giving me problems. In short, if you are receiving the error, "Couldn't show attachment", it means one of two things - 1.) you are trying to attach a file from the internal memory (remember, no other programs are allowed to access the internal memory, even gmail) or 2.) you are not using getAbsolutePath(). I found quite a few people that said you can't attach a file using uri.parse() and the you have to use uri.fromFile(), that is wrong, attached I show you how to attach a file and not get an error.
I hope this code helps you, and I hope you do not spend 1/10th of the time I did trying to figure this stuff out.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Calendar;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button mailb = (Button)findViewById(R.id.bmail);
final TextView confirmation = (TextView)findViewById(R.id.Confirmation);
mailb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
PrintWriter osw = new PrintWriter(Environment.getExternalStoragePublicDirectory(DOWNLOAD_SERVICE).toString() + "/output.txt"); //This creates a file in my public download directory
osw.println("Output Log: Report Tool");
osw.println("Date: " + java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime()));
osw.println("------------------------------------");
osw.println("Manufacturer: " + android.os.Build.MANUFACTURER);
osw.println("Model: " + android.os.Build.MODEL);
osw.println("Serial: " + android.os.Build.SERIAL);
osw.println("BootLoader: " + android.os.Build.BOOTLOADER);
osw.println("Build ID: " + android.os.Build.FINGERPRINT);
osw.println("------------------------------------");
try {
Process p = Runtime.getRuntime().exec("logcat -d -v long"); //This gets the dump of everything up to the button press
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
if(line.toString().contains("SIP_MESSAGE")){ //This parses out everything but SIP Messages
osw.println(line); }}}
catch (IOException e1) {confirmation.setText(e1.getMessage()); }
osw.flush();
osw.close();
} catch(Exception e){ confirmation.setText(e.getMessage()); }
String attach = Environment.getExternalStoragePublicDirectory(DOWNLOAD_SERVICE).getAbsolutePath() + "/output.txt"; //This is where you need to use the absolute path!!
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"MyEmail#Email.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "Error Report.");
i.putExtra(Intent.EXTRA_TEXT , "Please see the attached file...");
i.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + attach)); //This is where you attach the file
try {
startActivity(Intent.createChooser(i, "Send mail..."));}
catch (android.content.ActivityNotFoundException ex) {
confirmation.setText("There is no Email Client installed on this device.");}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
And finally, the permissions I used for this was READ_LOGS, WRITE_EXTERNAL, READ_EXTERNAL.
I hope you've enjoyed, and good luck.
Oops! Spoke too soon, you meant internal.
Why don't you try writing a file directly into your app directory instead of creating a folder. Check if it that works first.
For that you may do:
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
This is what you're looking for:
File outputDir = new File(Environment.getExternalStorageDirectory()
+ "/farmer survey");
outputDir.mkdirs();
File outputFile = new File(outputDir, "something.csv");
try {
FileOutputStream fos = new FileOutputStream(outputFile);
PrintWriter pw = new PrintWriter(fos);
pw.println(text);
pw.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You also need to add this permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Do you have the android.permission.READ_LOGS permission in your manifest?
For the email portion do you intent to send it automatically?
If so, I don't think it can be done in the background easily. The best is invoke the Gmail app with the output.txt attached as an attachment. Subsequently, you need to manually send it.
Otherwise the coding may be very long, see here:
Sending Email in Android using JavaMail API without using the default/built-in app
Or another way is to send out through SMS, this can be done in the background.

Android: How to open an unknown file type

I am developing a file explorer app in android.
How to handle files with unknown extensions? When I try to open such kind of file, its throwing ActivityNotFound exception. But I want the system to pop up list of apps so that we can manually choose an application to open it.
Can anyone help me here?
I am starting activity to open the file by binding the file and its extension to the intent.
Intent intent = new Intent(Intent.ACTION_VIEW);
MimeTypeMap mime = MimeTypeMap.getSingleton();
String ext = file.getName().substring(file.getName().lastIndexOf(".") + 1);
String type = mime.getMimeTypeFromExtension(ext);
intent.setDataAndType(Uri.fromFile(new File(file.toString())), type);
try
{
startActivity(intent);
}
catch(Exception e){}
ActivityNotFound is thrown when no application is registered that can handle specific file type. This means that the list of apps you want to show will be empty.
The most appropriate way to deal with he situation is to catch ActivityNotFound exception and show a toast notifying the user there are no appropriate applications to open the file.
All android browsers proceed in this manner.
I will leave this link here, that targets the same problem and has a little more detail to it (second answer, read comments): Launching an Activity based on a file in android

Categories