Having trouble when trying to md5 a string in android - android

On Android, I get the following error when I try to md5 a string:
"Performing stop of activity that is not resumed"
I need to attach the md5 to a URL.
Please help
//md5 code
MessageDigest digest;
try {
digest = MessageDigest.getInstance("MD5");
digest.reset();
digest.update(text.getBytes());
byte[] a = digest.digest();
int len = a.length;
StringBuilder sb = new StringBuilder(len << 1);
for (int i = 0; i < len; i++) {
sb.append(Character.forDigit((a[i] & 0xf0) >> 4, 16));
sb.append(Character.forDigit(a[i] & 0x0f, 16));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
// e.printStackTrace();
}
//request code
encryptedTaskId = MDConversion.MD5(taskId);
Log.v("inside doInBackground :: ", "inside doInBackground :: ");
totalUrl = baseUrl + "&access_token=" + accessToken + "&id=" + encryptedTaskId;
Log.v("fetch users to forward task url :: ", "url :: "+totalUrl);
HttpGet get = new HttpGet(totalUrl);
HttpClient client = new DefaultHttpClient();
HttpResponse response;
response = client.execute(get);

Try to use this static function:
public static final String md5(final String toEncrypt) {
try {
final MessageDigest digest = MessageDigest.getInstance("md5");
digest.update(toEncrypt.getBytes());
final byte[] bytes = digest.digest();
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
sb.append(String.format("%02X", bytes[i]));
}
return sb.toString().toLowerCase();
} catch (Exception exc) {
return ""; // Impossibru!
}
}

Related

building encryption SHA 1 from Parameter for android to json parse

I have problem with build Encryption from String to SHA 1 encrypt maybe in here can help me
This my Parameter
String AgentID = "7001";
String AgentPIN = "68820025";
String ScreetKey = "63e3cd0a";
String AgentTrxID = "201802090013";
String AgentStoreID = "01010101";
String pdam = pdam1;
String CustomerID =
edit_nomorpelangganpdam.getText().toString().trim();
String DateTimeRequest = (String)
DateFormat.format("yyyyMMddHHmmss", new Date());
And this my code for SHA 1
StringBuilder buf = new StringBuilder();
for (byte b : data) {
int halfbyte = (b >>> 4) & 0x0;
int two_halfs = 0;
do {
buf.append((0 <= halfbyte) && (halfbyte <= 9) ? (char) ('0' + halfbyte) : (char) ('a' + (halfbyte - 10)));
halfbyte = b & 0x0F;
} while (two_halfs++ < 1);
}
return buf.toString();
}
public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(text.getBytes("UTF-8"), 0, text.length());
byte[] sha1hash = md.digest();
return convertToHex(sha1hash);
}
I want to make like this Encryption
93d97a890c312a7f33ca2c393ec070a7e1b42cdc
Please try this code
// Call this method where you wont
encryptString("Your String value")
private static String encryptString(String value)
{
String sha1 = "";
try
{
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(value.getBytes("UTF-8"));
sha1 = byteToHexadecimal(crypt.digest());
}
catch(NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch(UnsupportedEncodingException e)
{
e.printStackTrace();
}
return sha1;
}
private static String byteToHexadecimal(final byte[] hash)
{
Formatter formatter = new Formatter();
for (byte b : hash)
{
formatter.format("%02x", b);
}
String result = formatter.toString();
formatter.close();
return result;
}

Why show error Cannot serialize?

My webservice;
[WebMethod]
public int insertNhanVien(string[] arr)
{
SqlConnection con = new SqlConnection();
// con.ConnectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=Bai1;Integrated Security=True";
con.ConnectionString = "server=.\\SQLEXPRESS;database=QLNV;uid=sa;pwd=123456";
con.Open();
int n = 0;
for (int i = 0; i < arr.Length; i++)
{
string[] s = arr[i].ToString().Split(',');
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Insert Into MUser(Ten,Tuoi) values(" + s[0].Replace("'", "''") + "," + s[1] + ")";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
n = cmd.ExecuteNonQuery();
}
return n;
}
And code in android:
private boolean insertNhanVient() {
boolean result = false;
try {
String NAMESPACE ="http://tempuri.org/";
String METHOD_NAME ="insertNhanVien";
String URL ="http://localhost:10829/WebSite/Service.asmx";
String SOAP_ACTIONS = NAMESPACE + "/" + METHOD_NAME;
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
String [] arr =new String[3];
arr[0]="le,12";
arr[1]="hoang,33";
arr[2]="nhung,23";
request.addProperty("arr", arr);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet=true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidhttpTranport = new HttpTransportSE(URL);
try {
androidhttpTranport.call(SOAP_ACTIONS, envelope);
} catch (IOException e3) {
result = false;
} catch (XmlPullParserException e3) {
result = false;
}
Object responseBody = null;
try {
responseBody = envelope.getResponse();
String t = responseBody.toString();
if (t.equals("1")) {
result = true;
}
} catch (SoapFault e2) {
result = false;
}
} catch (Exception e) {
result = false;
} finally {
}
return result;
}
Why show exception: java.lang.RuntimeException: Cannot serialize: [Ljava.lang.String;#4051d0a0 ?
you can't pass whole array.. so you have to use seprator ## in String ..and pass it service... and change on service respectivley.
String commasepratedString="";
for(int i=0;i<arr.length();i++)
{
if(i!=(arr.length-1))
{
commasepratedString=commasepratedString+arr[i]+"##";
}
else
{
commasepratedString=commasepratedString+arr[i];
}
}
request.addProperty("arr", commasepratedString);
and change service code like this way
[WebMethod]
public int insertNhanVien(string commasepratedString)
{
String arr[] = commasepratedString.Split('##');
SqlConnection con = new SqlConnection();
// con.ConnectionString = "Data Source=.\\SQLEXPRESS;InitialCatalog=Bai1; Integrated Security=True";
con.ConnectionString = "server=.\\SQLEXPRESS;database=QLNV;uid=sa;pwd=123456";
con.Open();
int n = 0;
for (int i = 0; i < arr.Length; i++)
{
string[] s = arr[i].ToString().Split(',');
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Insert Into MUser(Ten,Tuoi) values(" + s[0].Replace("'", "''") + "," + s[1] + ")";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
n = cmd.ExecuteNonQuery();
}
return n;
}
replace this line
request.addProperty("arr", arr);
with this
request.addProperty("arr", arr[0]);
you cannot pass whole array.you should pass one element of it.
Update
You can add multiple properties like
request.addProperty("prop1", arr[0]);
request.addProperty("prop2", arr[1]);
request.addProperty("prop3", arr[2]);

Android check download successful

For downloading stuff I work with the apache classes HTTPResponse HTTPClient etc.
I check for a valid download like this:
entity.writeTo(new FileOutputStream(outfile));
if(outfile.length()!=entity.getContentLength()){
long fileLength = outfile.length();
outfile.delete();
throw new Exception("Incomplete download, "+fileLength+"/"
+entity.getContentLength()+" bytes downloaded");
}
But it seems that the exception is never triggered. How to properly handle this? Is entity.getContentLength the length of the file on server or the amount of data received?
The file request should always come with a MD5 checksum. If you have an MD5 header then all you need to do is check that against the files generated MD5. Then your done, its better to do it this way as you can have a file with the same number of bytes but one byte gets garbled in transmission.
entity.writeTo(new FileOutputStream(outfile));
String md5 = response.getHeaders("Content-MD5")[0].getValue();
byte[] b64 = Base64.decode(md5, Base64.DEFAULT);
String sB64 = IntegrityUtils.toASCII(b64, 0, b64.length);
if (outfile.exists()) {
String orgMd5 = null;
try {
orgMd5 = IntegrityUtils.getMD5Checksum(outfile);
} catch (Exception e) {
Log.d(TAG,"Exception in file hex...");
}
if (orgMd5 != null && orgMd5.equals(sB64)) {
Log.d(TAG,"MD5 is equal to files MD5");
} else {
Log.d(TAG,"MD5 does not equal files MD5");
}
}
Add this class to your project:
public class IntegrityUtils {
public static String toASCII(byte b[], int start, int length) {
StringBuffer asciiString = new StringBuffer();
for (int i = start; i < (length + start); i++) {
// exclude nulls from the ASCII representation
if (b[i] != (byte) 0x00) {
asciiString.append((char) b[i]);
}
}
return asciiString.toString();
}
public static String getMD5Checksum(File file) throws Exception {
byte[] b = createChecksum(file);
String result = "";
for (int i = 0; i < b.length; i++) {
result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
}
return result;
}
public static byte[] createChecksum(File file) throws Exception {
InputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
MessageDigest complete = MessageDigest.getInstance("MD5");
int numRead;
do {
numRead = fis.read(buffer);
if (numRead > 0) {
complete.update(buffer, 0, numRead);
}
} while (numRead != -1);
fis.close();
return complete.digest();
}
}

Android : Streaming Audio TO a URL in Android using AudioRecord

I am trying to send the send voice data immediately to local server using audiorecord.. I am able to record the voice & stores it in SDcard.. but I want to store audio voice in buffer & sends immediate to the server using HTTP POST. How can I proceed.got struck..? I am creating this app in ICS i.e android 4.0.3 version.
got the solutions.. sending voice data as a jsonarray to server & recieve back as a json object. convert back jsonobject to short array n write to audiotrack then play back. here is sample code working.
public void SendAudio() {
String LOG_TAG = null;
long SAMPLE_INTERVAL = 1;
Log.e(LOG_TAG, "start send thread, thread id: ");
int bytes_read = 0;
int bytes_count = 0;
br = br % 5;
br++;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpClient httpclient_recv = new DefaultHttpClient();
// System.out.println("mmdata--------- " + value);
HttpPost httppost = new HttpPost("http://192.168.1.39/call");
HttpPost httppost_recv = new HttpPost("http://192.168.1.39/ping");
// Unix time stamp
long unixTime = System.currentTimeMillis();
String timestamp = String.valueOf(unixTime);
// Json Format
JSONObject holder = new JSONObject();
JSONObject holder_recv = new JSONObject();
JSONArray jArray = new JSONArray();
try {
holder.put("UserId", "1");
holder.put("TimeStamp", timestamp);
holder.put("SessionId", "1");
Queue<byte[]> qArray = new LinkedList<byte[]>();
qArray.add(bData);
byte[] tmparr = qArray.poll();
for (int i = 0; i < tmparr.length; i++) {
jArray.put(i, tmparr[i]);
}
System.out.println("send audio -- " + jArray);
holder.put("MMData", jArray.toString());
System.out.println("JSON -- " + holder.toString());
holder_recv.put("UserId", "1");
holder_recv.put("TimeStamp", timestamp);
holder_recv.put("SeqNo", "100");
holder_recv.put("SessionId", "0");
} catch (JSONException e1) {
e1.printStackTrace();
}
System.out.println("time " + timestamp);
try {
StringEntity se = new StringEntity(holder.toString());
StringEntity se_recv = new StringEntity(holder_recv.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
se_recv.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
httppost.setEntity(se);
httppost_recv.setEntity(se_recv);
HttpResponse response = httpclient.execute(httppost);
HttpResponse response_recv = httpclient_recv
.execute(httppost_recv);
if (response_recv != null) {
t = EntityUtils.toString(response_recv.getEntity());
System.out.println("after response -- " + t);
Queue<String> qe = new LinkedList<String>();
qe.add(t);
t = null;
System.out.println("on play side ...1 ");
try {
System.out.println("on play side ...2 ");
JSONObject get = new JSONObject(qe.poll());
// JSONArray jArray_recv = get.getJSONArray("MMData");
String mmdata = (String) get.get("MMData");
JSONObject temp2 = new JSONObject("{ \"MMData\" : "
+ mmdata + "}");
JSONArray jArray_recv = temp2.getJSONArray("MMData");
System.out.println("jsonarray -- " + jArray_recv);
// String timeData = (String) get.get("TimeStamp");
String userData = (String) get.get("UserId");
// String sessionId = (String) get.get("TimeStamp");
System.out.println("on play side ...3 ");
// if (Long.valueOf(timeData) > ts)
{
// ts = Long.valueOf(timeData);
System.out.println("on play side ...4 ");
if (at != null) {
System.out.println("on play side ...5 ");
byte[] shortArray = new byte[jArray_recv
.length()];
for (int i = 0; i < jArray_recv.length(); i++) {
shortArray[i] = (byte) jArray_recv
.getInt(i);
}
jArray_recv = null;
System.out.println("recv audio -- " + br
+ " ----" + shortArray);
byte[] temp = shortArray;
shortArray = null;
byte[] bArray = temp;
temp = null;
byte[][] newbarray = new byte[5][1024];
newbarray[br - 1] = bArray;
byte[] sbayyay = new byte[1024 * 5];
System.arraycopy(bArray, 0, sbayyay,
(br - 1) * 1024, bArray.length);
if (br == 5) {
for (int i = 0; i < 5; i++) {
System.out.println("in for---" + i
+ "----" + sbayyay.length);
// System.arraycopy(newbarray[i], 0,
// sbayyay, i * 1024,
// bArray.length);
}
System.out.println("bsbsbsbs --- "
+ new String(sbayyay));
at.write(sbayyay, 0, sbayyay.length);
at.play();
}
}
else {
Log.d("Audio",
"audio track is not initialised ");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
System.out.println("Exception");
e.printStackTrace();
}
bytes_count += bytes_read;
Log.d(LOG_TAG, "bytes_count : " + bytes_count);
Thread.sleep(SAMPLE_INTERVAL, 0);
} catch (InterruptedException ie) {
Log.e(LOG_TAG, "InterruptedException");
}
}

Fail to split downloaded txt file

I have a String that I try to split. The following code works
lsSagor = "some text\n Some more text\n More text~Text again\n Text\n text~Some text ..."
final String[] laList = lsSagor.split("~");
String[] laSaga = laList[0].split("\n");
Gives:
laSaga[0] => some text
laSaga[1] => some more text
laSaga[2] => More text
But if I download the textfile, it fails to split and gives:
laSaga[0] => "some text\n Some more text\n More text"
So it seems the first split works, but not the second.
Here is the code I use to download the file
String lsSagor = getFileFromUrl(BASEURL+"/sagor.txt");
public static String getFileFromUrl(String url)
{
InputStream content = null;
try
{
HttpGet httpGet = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
// Execute HTTP Get Request
HttpResponse response = httpclient.execute(httpGet);
content = response.getEntity().getContent();
}
catch (Exception e)
{
//handle the exception !
}
BufferedReader rd = new BufferedReader(new InputStreamReader(content), 4096);
String line;
StringBuilder sb = new StringBuilder();
try {
while ((line = rd.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
rd.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb.toString();
}
From the documentation
I don't think you will find your string contains any newline character to split on, you would need to do
while ((line = rd.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
to get that and I'm sure there is an easier way to just read it newlines and all in the first place.
Hi I think the problem is in String.split() function
Old method but work :)
public static String[] splitString(String str, char separator)
{
String[] retVal = null;
int length = str.length();
int size = 1;
int jIndx = 0;
int expressionLength = 0;
while ((jIndx = str.indexOf(separator, jIndx + 1)) != -1)
{
size++;
}
retVal = new String[size];
jIndx = 0;
char[] charArray = str.toCharArray() ;
for (int index = 0; index < length; index++)
{
if (charArray[index] == separator)
{
retVal[jIndx] = str.substring(index - expressionLength, index);
jIndx++;
expressionLength = 0;
}
else
expressionLength++;
if (index + 1 == length)
{
retVal[jIndx] = str.substring(index + 1 - expressionLength, index + 1);
}
}
return retVal;
}
This is the (not so beautiful) solution
lsSagor = "some text# Some more text# More text~Text again\n Text# text~Some text ..."
String lsSagor = getFileFromUrl(BASEURL+"/sagor.txt");
final String[] laList = lsSagor.split("~");
giAntalSagor = laList.length;
String[] laSaga = laList[0].split("#");
final String[] guiLaList = new String[giAntalSagor];
for (int i = 0; i < giAntalSagor; i++)
{
guiLaList[i] = laList[i].replaceAll("#", "\n");
}
guiLaList is used for layout with "\n" and the other list laList to get the information I wanted.

Categories

Resources