Call decryption method from one activity to adapter - android

I would like to ask how to call my decryption method from one activity to another(Adapter).
MessageActivity.java here is my decryption method:
private String AESDecriptionMetod(String string) throws UnsupportedEncodingException {
byte[] EncriptedByte = string.getBytes("ISO-8859-1");
String decryptedString = string;
byte[] decryption;
try {
decipher.init(cipher.DECRYPT_MODE, secretKeySpec);
decryption = decipher.doFinal(EncriptedByte);
decryptedString = new String(decryption);
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
}
return decryptedString;
}
MessageAdapter.java where I want to call decryption method:
#Override
public void onBindViewHolder(#NonNull MessageAdapter.ViewHolder holder, int position) {
Chat chat = mChat.get(position);
stringMessage = chat.getMessage().toString();
stringMessage = stringMessage.substring(1, stringMessage.length()-1);
String[] stringMessageArrey = stringMessage.split(", ");
Arrays.sort(stringMessageArrey);
String[] stringFinal = new String[stringMessageArrey.length];
for(int i = 0; i<stringMessageArrey.length; i++){
String[] stringKeyValue = stringMessageArrey[i].split("=", 2);
try {
stringFinal[i]= AESDecriptionMetod(stringKeyValue[1]);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return stringFinal.toString();
}
holder.show_message.setText(stringFinal);
if (imageurl.equals("default")){
holder.profile_image.setImageResource(R.mipmap.ic_launcher);
} else {
Glide.with(mContext).load(imageurl).into(holder.profile_image);
}
}
And how to implement stringFinal in holder.show_message.setText( ??? );
Thanks for any answer!

Related

Multiuserchat InvitationListener Smack: 4.1.0 not getting called

I have already gone through related questions on stack but all in vain. I am not getting callback in Invitation Listener. Any help will be appreciated.
MultiUserChatListener
MultiUserChatManager.getInstanceFor(connection).addInvitationListener(new InvitationListener() {
#Override
public void invitationReceived(XMPPConnection conn, MultiUserChat room, String inviter, String reason, String password, Message message) {
String nickname = AppSharedPereference.getInstance(mContext).getUserName();
try {
mchat.join(nickname);
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
});
}
sendInvitation Method
public void sendInvites(ArrayList<ContactData.Usercontactsdetail> usercontactsdetail) {
try {
for (int i = 0; i < usercontactsdetail.size(); i++) {
String userID = usercontactsdetail.get(i).getContactid();
String user = userID + "#" + connection.getHost();
mchat.invite(user,
userID + "_user");
}
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}finally {
usercontactsdetail = null;
}
try {
mchat.sendMessage("New group created");
} catch (SmackException.NotConnectedException e1) {
e1.printStackTrace();
}
}

Can not resolve getAssets() method from inside a java file: Android

I have created a file
inside assests folder and now I want to read the file from a java class and pass it to another function in the same class but for some reason i am unable to use getAssest() method. Please help!
public void configuration()
{
String text = "";
try {
InputStream is = getAssets().open("config.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
public IExtraFeeCalculator getExtraFeeCalculator()
{
if(efCalculator==null)
{
if(configuration(Context context) == "extrafeeCalculaotor")
{
String className = System.getProperty("extraFeeCalculator.class.name");
try {
efCalculator = (IExtraFeeCalculator)Class.forName(className).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
return efCalculator;
}
You should try
getResources().getAssets().open("config.txt")
instead of
context.getAssets().open("config.txt");
Change your Method with Single Parameter Context ....
Pass Context from where you Call this Method..
public void configuration(Context context)
{
String text = "";
try {
InputStream is = context.getAssets().open("config.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
Yes now as per i think you are not aware from java structure...
Suppose you have this YOUR_CLASS_NAME.java
public void YOUR_CLASS_NAME{
Context context;
YOUR_CLASS_NAME(Context context){
this.context=context;
}
public void configuration(Context context)
{
String text = "";
try {
InputStream is = getAssets().open("config.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
public IExtraFeeCalculator getExtraFeeCalculator()
{
if(efCalculator==null)
{
if(configuration(context) == "extrafeeCalculaotor")
{
String className = System.getProperty("extraFeeCalculator.class.name");
try {
efCalculator = (IExtraFeeCalculator)Class.forName(className).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
return efCalculator;
}
}
Use this Code
BufferedReader reader = null;
try {
StringBuilder returnString = new StringBuilder();
reader = new BufferedReader(
new InputStreamReader(getAssets().open("filename.txt")));
String mLine;
while ((mLine = reader.readLine()) != null) {
//process line
returnString.append(mLine );
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}

How to save an application's data?

I have written a Web View app, which logs you into 12 different sites (sign in) which works pretty fine. However, i am trying to figure out a way to backup my web view's data (so that all the login credentials are saved) to SD card. the only way i have found is to copy the root/data/data/com.example/your app folder.
How do i copy this folder somewhere to my SD card using root command on the click of a button?
this is how i access and delete the data folder
private void clear() {
String cmd = "pm clear com.wagtailapp";
ProcessBuilder pb = new ProcessBuilder().redirectErrorStream(true)
.command("su");
Process p = null;
try {
p = pb.start();
} catch (IOException e) {
e.printStackTrace();
}
StreamReader stdoutReader = new StreamReader(p.getInputStream(),
CHARSET_NAME);
stdoutReader.start();
out = p.getOutputStream();
try {
out.write((cmd + "\n").getBytes(CHARSET_NAME));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
out.write(("exit" + "\n").getBytes(CHARSET_NAME));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
p.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
String result = stdoutReader.getResult();
}
}
streamreader.java
class StreamReader extends Thread {
private InputStream is;
private StringBuffer mBuffer;
private String mCharset;
private CountDownLatch mCountDownLatch;
StreamReader(InputStream is, String charset) {
this.is = is;
mCharset = charset;
mBuffer = new StringBuffer("");
mCountDownLatch = new CountDownLatch(1);
}
String getResult() {
try {
mCountDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
return mBuffer.toString();
}
#Override
public void run() {
InputStreamReader isr = null;
try {
isr = new InputStreamReader(is, mCharset);
int c = -1;
while ((c = isr.read()) != -1) {
mBuffer.append((char) c);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (isr != null)
isr.close();
} catch (IOException e) {
e.printStackTrace();
}
mCountDownLatch.countDown();
}
}
}

How to avoid EOFExeption by read from socket in AsyncTask that repeats in handle?

I need to update data from server every second. I create handle with AsyncTask, that repeats every second. This works, but about a minute it crushes with EOFException by reading from DataInputStream.
Handler
handler.postDelayed( new Runnable() {
#Override
public void run() {
tickListAdapter = new TickListAdapter(TickActivity.this,tickList);
tickListView.setAdapter(tickListAdapter);
AsyncTCPSend tcpSend= new AsyncTCPSend(address,serverPort, line);
tcpSend.execute();
Log.e(TAG,"update");
handler.postDelayed( this, 1000 );
}
},1000 );
AsyncTask
public class AsyncTCPSend extends AsyncTask<Void, Void, Void> {
String address;
int port;
String message;
String response=null;String lineRead = null;
Socket socket;
int count=1;
OutputStream os;
DataInputStream dis;
AsyncTCPSend(String addr, int p, String mes) {
address = addr;
port = p;
message = mes;
}
#Override
protected Void doInBackground(Void... params) {
socket = null;
try {
socket = new Socket(address, port);
os = socket.getOutputStream();
dis = new DataInputStream(socket.getInputStream());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (!isConnect){
if (connect()){
isConnect = true;
Log.e("CLIENT","now is connected");
getTick();
}
}
return null;
}
public boolean connect(){
try {
Log.e("CLIENT","CONNECTED");
String command = "AUTH_START";
byte[] queryBody = null;
queryBody = command.getBytes("UTF-16LE");
byte[] message = new byte[queryBody.length];
for (int i = 0; i < message.length; ++i)
os.write(message,0,message.length);
Log.e(TAG,"AUTH_START");
String srv = null;
srv = function();
if (srv != null){
if (srv.equals("Error")){
Log.e("CLIENT","Error");
return false;
} else {
String auth_answer = "AUTH_ANSWER";
byte[] authBody = auth_answer.getBytes("UTF-16LE");
Log.e(TAG,"AUTH_ANSWER");
os.write(authBody,0,authBody.length);
srv = function();
if (srv.equals("Error")){
Log.e("CLIENT","Error");
return false;
} else {
Log.e(TAG,"AUTH SUCCESS!!!");
return true;
}
}
} else {
return false;
}
}
catch (UnknownHostException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public String getTick(){
String tick = "TICK";
try {
tickBody = tick.getBytes("UTF-16LE");
os.write(tickBody,0,tickBody.length);
String srv = function();
return srv;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
String function(){
String srv = null;
int len = 0;
try {
len = dis.readInt(); //EOFException is here!!!!
byte[] data = new byte[1024];
if (len > 0) {
dis.read(data, 0, data.length);
}
String out = new String(data,"UTF-16");
if (out.indexOf("Done")>0){
if (out.indexOf("STAT")>0 ||out.indexOf("AST")>0){
srv = out;
}
else {
srv = out.substring(out.indexOf("SRV")+9,out.indexOf("SRV")+41);
}
} else {
srv = "Error";
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return srv;
}
#Override
protected void onPostExecute(Void result) {
Log.e("CLIENT","onPostExecute");
super.onPostExecute(result);
}
}
}
Anybody know why appear EOFException about a minute? How to avoid?
P.S. To obtain the necessary information from the server, I must first pass authentication
Why this exception occurs?
According to Docs
Signals that an end of file or end of stream has been reached unexpectedly during input.
This exception is mainly used by data input streams to signal end of stream. Note that many other input operations return a special value on end of stream rather than throwing an exception.
look upon this answer
The problem was solved by changing the method. I added two threads for output and input inside AsyncTask

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

Categories

Resources