How to use a progress dialog for `AESCrypt.encrypt` - android

I want to use progress dialog in function in Android Studio. This form will appear until the code is executed:
protected boolean encryptFile() {
/*
* set input file name
*/
String encryptFileName = mEditText.getText().toString();
/*
* set hint
*/
String hint = mHintText.getText().toString();
if(hint.isEmpty()){hint=null;}
/*
* set password
*/
String password = mPassText.getText().toString();
/*
* select encrypted file name
*/
String encryptedFileName = mEditText.getText().toString()+".enc";
if(hint!=null){
encryptedFileName = mEditText.getText().toString() + "(hint-" +hint+ ").enc";
}
/*
* Encrypt
*/
try {
AESCrypt crypt = new AESCrypt(password);
crypt.encrypt(2, encryptFileName, encryptedFileName);
return true;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (GeneralSecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
public void encrypt(int version, String fromPath, String toPath)
throws IOException, GeneralSecurityException {
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(fromPath));
debug("Opened for reading: " + fromPath);
out = new BufferedOutputStream(new FileOutputStream(toPath));
debug("Opened for writing: " + toPath);
encrypt(version, in, out);
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}

Related

clearing multiple apps' data android

I'm able to clear a single package name's data through this snippet. However, i want it to handle more than one package names. in other words, it should clear two more package names' data
private void clearData() {
//"com.uc.browser.en"
//"pm clear com.sec.android.app.sbrowser"
String cmd = "pm clear com.sec.android.app.sbrowser" ;
ProcessBuilder pb = new ProcessBuilder().redirectErrorStream(true)
.command("su");
Process p = null;
try {
p = pb.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// We must handle the result stream in another Thread first
StreamReader stdoutReader = new StreamReader(p.getInputStream(),
CHARSET_NAME);
stdoutReader.start();
out = p.getOutputStream();
try {
out.write((cmd + "\n").getBytes(CHARSET_NAME));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
out.write(("exit" + "\n").getBytes(CHARSET_NAME));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
p.waitFor();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String result = stdoutReader.getResult();
}
}
The ProcessCommandsSU class starts an su process in which to run a list of commands, and provides an interface to deliver the output to an Activity asynchronously. Unlike the example you're following, this class will not block the UI thread. The Activity must implement the OnCommandsReturnListener interface.
public class ProcessCommandsSU extends Thread {
public interface OnCommandsReturnListener {
public void onCommandsReturn(String output);
}
private final Activity activity;
private final String[] cmds;
public ProcessCommandsSU(Activity activity, String[] cmds) {
if(!(activity instanceof OnCommandsReturnListener)) {
throw new IllegalArgumentException(
"Activity must implement OnCommandsReturnListener interface");
}
this.activity = activity;
this.cmds = cmds;
}
public void run() {
try {
final Process process = new ProcessBuilder()
.redirectErrorStream(true)
.command("su")
.start();
final OutputStream os = process.getOutputStream();
final CountDownLatch latch = new CountDownLatch(1);
final OutputReader or = new OutputReader(process.getInputStream(), latch);
or.start();
for (int i = 0; i < cmds.length; i++) {
os.write((cmds[i] + "\n").getBytes());
}
os.write(("exit\n").getBytes());
os.flush();
process.waitFor();
latch.await();
process.destroy();
final String output = or.getOutput();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
((OnCommandsReturnListener) activity).onCommandsReturn(output);
}
}
);
}
catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
private class OutputReader extends Thread {
private final InputStream is;
private final StringBuilder sb = new StringBuilder();
private final CountDownLatch latch;
public OutputReader(InputStream is, CountDownLatch latch) {
this.is = is;
this.latch = latch;
}
public String getOutput() {
return sb.toString();
}
public void run() {
try {
final BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
}
catch (IOException e) {
e.printStackTrace();
}
latch.countDown();
}
}
}
Using the class is quite simple. We first ensure that our Activity implements the interface. We then create an instance, passing the Activity and our array of commands in the constructor, and call its start() method. In the following example, it's assumed that the Activity has a TextView named textOutput to display the returned output:
public class MainActivity extends Activity
implements ProcessCommandsSU.OnCommandsReturnListener {
...
#Override
public void onCommandsReturn(String output) {
textOutput.append(output + "\n");
}
private void runCommands() {
final String[] cmds = {
"ping -c 5 www.google.com",
"pm list packages android",
"chdir " + Environment.getExternalStorageDirectory(),
"ls"
};
new ProcessCommandsSU(MainActivity.this, cmds).start();
}
}
My device is not rooted, so this was tested with the commands you see in the code above. Simply replace those commands with your pm clear commands.

android, Read content of 100-300 files from FTP folder... Hangs

I am using RetrieveFilestream method with BufferedInputStream in a for loop. I am closing all
streams after processing each file and also adding ftp complete pending command.
Every thing works as expected in my test environment with few files. But in realtime data where there are 200-300 files, it hangs somewhere.
It is not throwing any exception making it difficult to debug. Cannot debug one by one. Any help?
Here is my code Block.
public String LoopThroughFiles(FTPClient myftp, String DirectoryName)
{
boolean flag=false;
String output="";
InputStream inStream=null;
BufferedInputStream bInf= null;
StringBuilder mystring = new StringBuilder();
progressBar = (ProgressBar) findViewById(R.id.progressBar);
try {
flag= myftp.changeWorkingDirectory(DirectoryName);
if(flag==true)
{
FTPFile[] files = myftp.listFiles();
progressBar.setMax(files.length);
String fname="";
myftp.enterLocalPassiveMode();
if(files.length > 0)
{
int n=0;
for (FTPFile file : files)
{
n=n+1;
int r= progressBar.getProgress();
progressBar.setProgress(r+n);
fname=file.getName();
// String path= myftp.printWorkingDirectory();
if(fname.indexOf("txt") != -1)
{
inStream = myftp.retrieveFileStream(fname);
int reply = myftp.getReplyCode();
if (inStream == null || (!FTPReply.isPositivePreliminary(reply) && !FTPReply.isPositiveCompletion(reply))) {Log.e("error retrieving file",myftp.getReplyString()); }
bInf=new BufferedInputStream (inStream);
int bytesRead;
byte[] buffer=new byte[1024];
String fileContent=null;
while((bytesRead=bInf.read(buffer))!=-1)
{
fileContent=new String(buffer,0,bytesRead);
mystring.append(fileContent);
}
mystring.append(",");
bInf.close();
inStream.close();
boolean isSucess= myftp.completePendingCommand();
if(isSucess == false)
Log.e("error retrieving file","Failed to retrieve the stream for " + fname);
}
}
flag= myftp.changeToParentDirectory();
}
}
}
catch (java.net.UnknownHostException e) {
e.printStackTrace();
Log.e("readfile,UnknownHost",e.getMessage());
}
catch (java.io.IOException e) {
e.printStackTrace();
Log.e("readfile,IO",e.getMessage());
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("readfile,General",e.getMessage());
}
finally
{
try {
output = mystring.toString();
if(bInf != null)
bInf.close();
if(inStream != null)
inStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("readfile,finallyblock",e.getMessage());
}
}
return output;
}

How to show selection marker on EditText

In my app I programmatically set start and end selection on EditText via setSelection(int start, int end) method, but user doesn't see selection markers. How can I show markers programmatically?
When I said marker I mean this:
I found answer. Hope it will help someone. Need use method show when need show pins and in onSelectionChange need use hidePins, because pins don't hide after used showPins.
public void showPins() {
Class TV = TextView.class;
try {
Field GetEditor = TV.getDeclaredField("mEditor");
GetEditor.setAccessible(true);
Object editor = GetEditor.get(this);
Method GetInsController = editor.getClass().getDeclaredMethod("getSelectionController");
GetInsController.setAccessible(true);
Object insController = GetInsController.invoke(editor);
if (insController != null) {
Method Show = insController.getClass().getDeclaredMethod("show");
Show.setAccessible(true);
Show.invoke(insController);
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
public void hideTwoPins() {
Class TV = TextView.class;
try {
Field GetEditor = TV.getDeclaredField("mEditor");
GetEditor.setAccessible(true);
Object editor = GetEditor.get(this);
Method GetInsController = editor.getClass().getDeclaredMethod("getSelectionController");
GetInsController.setAccessible(true);
Object insController = GetInsController.invoke(editor);
if (insController != null) {
Method hide = insController.getClass().getDeclaredMethod("hide");
hide.setAccessible(true);
hide.invoke(insController);
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
custom method
/**
* Method allocates filtering substring in all contacts yellow color,
* that satisfy the user's search
* #param inputText - DisplayName
* filtText - filtering Text
* #return String with allocating substring (Spannable)
*/
public static Spannable changeBackgroungFiltText(CharSequence inputText, String filtText, int color) {
Spannable str = null;
if(inputText != null)
{
String inputStr = inputText.toString();
String inputLowerCaseStr = inputStr.toLowerCase();
String filtLowerCaseStr = filtText.toLowerCase();
// Spannable str = new SpannableStringBuilder(inputStr);
str = new SpannableStringBuilder(inputStr);
if (filtText.length() != 0)
{
int indexStart = 0;
while (true)
{
int indexCur = inputLowerCaseStr.indexOf(filtLowerCaseStr, indexStart);
if (indexCur != -1) {
int start = indexCur;
int end = indexCur + filtText.length();
int flag = Spannable.SPAN_EXCLUSIVE_EXCLUSIVE;
str.setSpan(new ForegroundColorSpan(color),start, end, flag);
//str.setSpan(new BackgroundColorSpan(highlightColor), start, end, flag);
indexStart = indexCur + 1;
} else {
return str;
}
}
} else {
return str;
}
}
return str;
}
Here is how to show the left or right pin,
based on the code of the second post (thanks a lot by the way).
public static void showSelectionPins(TextView textView, boolean left, boolean right) {
Class TV = TextView.class;
try {
Field GetEditor = TV.getDeclaredField("mEditor");
GetEditor.setAccessible(true);
Object editor = GetEditor.get(textView);
Method GetInsController = editor.getClass().getDeclaredMethod("getSelectionController");
GetInsController.setAccessible(true);
Object insController = GetInsController.invoke(editor);
if (insController != null) {
Method Show = insController.getClass().getDeclaredMethod("show");
Show.setAccessible(true);
Show.invoke(insController);
}
/**
* since the {#code mStartHandle} and {#code mEndHandle} are created lazily<br/>
* we must access them after {#code show()} has been called.
*/
if (!left) {
Field SelectionStartHandleView = insController.getClass().getDeclaredField("mStartHandle");
SelectionStartHandleView.setAccessible(true);
Object startHandleView = SelectionStartHandleView.get(insController);
Method handleViewHideMethod = startHandleView.getClass().getSuperclass().getDeclaredMethod("hide");
handleViewHideMethod.setAccessible(true);
handleViewHideMethod.invoke(startHandleView);
}
if (!right) {
Field SelectionEndHandleView = insController.getClass().getDeclaredField("mEndHandle");
SelectionEndHandleView.setAccessible(true);
Object endHandleView = SelectionEndHandleView.get(insController);
Method handleViewHideMethod = endHandleView.getClass().getSuperclass().getDeclaredMethod("hide");
handleViewHideMethod.setAccessible(true);
handleViewHideMethod.invoke(endHandleView);
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
Here is how to show the insertion pin,
also based on the code of the second post (thanks a lot by the way).
public static void showInsertionPin(TextView textView) {
Class TV = TextView.class;
try {
Field GetEditor = TV.getDeclaredField("mEditor");
GetEditor.setAccessible(true);
Object editor = GetEditor.get(textView);
Method GetInsertionPointCursorController = editor.getClass().getDeclaredMethod("getInsertionController");
GetInsertionPointCursorController.setAccessible(true);
Object insController = GetInsertionPointCursorController.invoke(editor);
if (insController != null) {
Method hide = insController.getClass().getDeclaredMethod("show");
hide.setAccessible(true);
hide.invoke(insController);
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}

Filter log information, BufferedWriter in-file invalid

I have a log package.I want to filter the log.e, and save it to another file. But I find BufferedWriter can not reach the expected effect. Such as the two lines in log file below can not store another file.
E/Vold ( 96): Sleep 2s to make sure that coldboot() events are handled
E/WindowManager( 244): setEventDispatching false
attach code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class LogSpider {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader("C:\\Users\\Administrator\\Desktop\\log.txt"));
String line = "";
try {
while((line = bufferedReader.readLine())!=null)
{
Parseelog(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
bufferedReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void Parseelog(String line)
{
BufferedWriter bufferedWriter = null;
try {
bufferedWriter = new BufferedWriter(new FileWriter("C:\\Users\\Administrator\\Desktop\\logspider2.txt"));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
//Pattern pattern = Pattern.compile("[\\w[.-]]+\\#[\\w[.-]]{2,}\\.[\\w[.-]]+");
Pattern pattern = Pattern.compile("^E.*");
Matcher matcher = pattern.matcher(line);
while(matcher.find())
{
String string = new String(matcher.group());
string += "\n";
System.out.println(string); //here can print the search results
try {
bufferedWriter.write(string, 0, string.length());
bufferedWriter.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
bufferedWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
The problem with you code was that you where opening the logspider2.txt file every time you want to write the matching line. So it was overwriting all the previous data. To solve the issue you need to open your file in the append mode as follows:
bufferedWriter = new BufferedWriter(
new FileWriter(
"F:\\praful\\androidworkspace_2\\Test\\src\\logspider2.txt",true));
I tried you code and made some modification to make it work. Following is the working code:
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(
"F:\\praful\\androidworkspace_2\\Test\\src\\logs.txt"));
String line = "";
try {
while ((line = bufferedReader.readLine()) != null) {
Parseelog(line);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
bufferedReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void Parseelog(String line) {
BufferedWriter bufferedWriter = null;
// Pattern pattern =
// Pattern.compile("[\\w[.-]]+\\#[\\w[.-]]{2,}\\.[\\w[.-]]+");
Pattern pattern = Pattern.compile("^E.*");
Matcher matcher = pattern.matcher(line);
try {
bufferedWriter = new BufferedWriter(
new FileWriter(
"F:\\praful\\androidworkspace_2\\Test\\src\\logspider2.txt",true));
while (matcher.find()) {
String string = new String(matcher.group());
string += "\n";
System.out.println(string); // here can print the search results
bufferedWriter.write(string);
}
bufferedWriter.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Please changed the file path to your local paths. Hope it help you..

File reading not working for android

I am an android newbie and wrote this code for file handling but for some reason i am always getting back null values from the file. I also tried using readline() but got the same result. Would appreciate any help.
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
String file = "test123";
try
{
OutputStream out = v.getContext().openFileOutput(file, MODE_PRIVATE);
InputStream in = v.getContext().openFileInput(file);
WriteFile(out);
String str = ReadFile(in);
Toast.makeText(v.getContext(), str, Toast.LENGTH_LONG);
} catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public static void WriteFile(OutputStream out)
{
OutputStreamWriter tmp = new OutputStreamWriter(out);
try
{
for (int i = 0 ; i < 10; i++)
{
tmp.write(i);
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String ReadFile(InputStream in)
{
InputStreamReader tmp = null;
String str = "";
tmp = new InputStreamReader(in);
BufferedReader reader=new BufferedReader(tmp);
try
{
for (int i = 0; i < 10; i++)
{
str += " " + reader.readLine();
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
}
String file = "test123";
So, the path of your file should be {root}/test123
Try defining a path were you can access to see if it has written something. (usually : /mnt/storage/your_file)
Then, you'll be able to determine if the Write/Read process works or not
Note : Take a look at FileOutputStream, it already implements lots of useful methods

Categories

Resources