More secure encryption class using salt - Java for Android App Development

Continuing with the theme from my last thread where I posted a simple class for encrypting strings using the SHA-512 hashing algorithm, here is an improved version that generates a random 20 byte salt to add in with the string to be hashed. This is then hashed providing greater security.
Due to the random generation of the salt each time a string is hashed, this makes it pretty much impossible to get the same hash for a string, therefore once the salt has been generated the first time round it is stored in sharedPreferences for future uses so that you can use it for checking matches etc
Method of converting the bytes to hex string adapted from maybeWeCouldStealAVan's method @ stackoverflow.
Code:
public class Crypto {
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
protected static String SHA512(String string, Context context) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-512");
String salt = getSalt(context);
md.update(salt.getBytes());
byte[] bytes = md.digest(string.getBytes());
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
private static String getSalt(Context context) throws NoSuchAlgorithmException {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
String salt = preferences.getString("salt", null);
if (salt == null) {
byte[] saltBytes = new byte[20];
SecureRandom.getInstance("SHA1PRNG").nextBytes(saltBytes);
salt = new String(saltBytes);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("salt", salt).commit();
}
return salt;
}
}
Usage:
Code:
String example = "example";
try {
example = Crypto.SHA512(example, context);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}

Thanks for sharing, it's quite usefull ! I will include it to my project

Jonny said:
Continuing with the theme from my last thread where I posted a simple class for encrypting strings using the SHA-512 hashing algorithm, here is an improved version that generates a random 20 byte salt to add in with the string to be hashed. This is then hashed providing greater security.
Due to the random generation of the salt each time a string is hashed, this makes it pretty much impossible to get the same hash for a string, therefore once the salt has been generated the first time round it is stored in sharedPreferences for future uses so that you can use it for checking matches etc
Method of converting the bytes to hex string adapted from maybeWeCouldStealAVan's method @ stackoverflow.
Code:
public class Crypto {
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
protected static String SHA512(String string, Context context) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-512");
String salt = getSalt(context);
md.update(salt.getBytes());
byte[] bytes = md.digest(string.getBytes());
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
private static String getSalt(Context context) throws NoSuchAlgorithmException {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
String salt = preferences.getString("salt", null);
if (salt == null) {
byte[] saltBytes = new byte[20];
SecureRandom.getInstance("SHA1PRNG").nextBytes(saltBytes);
salt = new String(saltBytes);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("salt", salt).commit();
}
return salt;
}
}
Usage:
Code:
String example = "example";
try {
example = Crypto.SHA512(example, context);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
Click to expand...
Click to collapse
Thanks
Gesendet von meinem LG-D855 mit Tapatalk

Related

[Q] app slow down when using sqlite database

I am trying to create a circular buffer using sqlite. For some reason every time I instantiate my db access class, the os start skipping frames (I am using the emulator to run my code).
02-22 20:22:03.172: I/Choreographer(860): Skipped 628 frames! The application may be doing too much work on its main thread.
I do not understand what I am doing wrong. I am calling the database class from an intentService (I assume this should not slow down the main thread at all) as follows:
Code:
private SqliteLog mSqliteLog;
mSqliteLog = new SqliteLog(context);
mSqliteLog.writelogInformation("sleepMode", "ON");
I added my code at the end of this message
Code:
/**
* SqliteLog
*
*
* Base class for sqliteLog control
*
*
*/
public class SqliteLog {
// Debug log tag
private static final String tag = "SqliteLog";
// Version of database
private static final int DATABASE_VERSION = 1;
// Name of database
private static final String DATABASE_NAME = "log";
// Table of database
private static final String TABLE_NAME = "log";
public static final String ROWID_NAME = "id";
public static final String PREFERENCE_NAME = tag + "Pref";
public static final String COLUMN_LOGNUMBER = "logNumber";
public static final String COLUMN_TIME = "time";
public static final String COLUMN_FUNCTION = "function";
public static final String COLUMN_DESCRIPTION = "description";
public static final int TABLE_SIZE = 20;
private static final String DATABASE_CREATE ="create table " + TABLE_NAME + " (" + ROWID_NAME + " integer primary key autoincrement, " +
COLUMN_LOGNUMBER + " INTEGER NOT NULL, " +
COLUMN_TIME + " TEXT NOT NULL, " +
COLUMN_FUNCTION + " TEXT NOT NULL, " +
COLUMN_DESCRIPTION + " TEXT NOT NULL " +
");";
//The context of the calling class;
private Context thisContext;
/**
* <p>Constructor for SqliteLog
* @param context :- Context of calling class
*
*/
public SqliteLog(Context context) {
Log.d(tag,"SqliteLog constructor called");
thisContext = context;
}
/**
* writelogInformation :- Writes a row into the log table
*
*/
public void writelogInformation(String functionName, String descriptionInfo) {
// Retrieve preferences
SharedPreferences SqliteLogPref = thisContext.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
int logNumber = SqliteLogPref.getInt("logNumber", 1);
// Open database for writing
DatabaseHelper databaseHelper = new DatabaseHelper(thisContext);
SQLiteDatabase sQLiteDatabase = databaseHelper.getWritableDatabase();
// Define the column name and data
ContentValues values = new ContentValues();
values.put(COLUMN_LOGNUMBER, logNumber);
values.put(COLUMN_TIME, getTime());
values.put(COLUMN_FUNCTION, functionName);
values.put(COLUMN_DESCRIPTION, descriptionInfo);
// Update database
sQLiteDatabase.update(TABLE_NAME, values, null, null);
// Close database
databaseHelper.close();
// Test if next database update will need to be wrapped around
logNumber = (logNumber % TABLE_SIZE) + 1;
// Store preferences
SharedPreferences.Editor editor = SqliteLogPref.edit();
editor.putInt("logNumber", logNumber);
editor.commit();
}
/**
* clearLog :- Erase all information from table
*
*/
public void clearLog() {
// Retrieve preferences
SharedPreferences SqliteLogPref = thisContext.getSharedPreferences(PREFERENCE_NAME, 0);
// Store preferences
SharedPreferences.Editor editor = SqliteLogPref.edit();
editor.putInt("logNumber", 1);
editor.commit();
// Delete all rows
DatabaseHelper databaseHelper = new DatabaseHelper(thisContext);
SQLiteDatabase sQLiteDatabase = databaseHelper.getReadableDatabase();
sQLiteDatabase.delete (TABLE_NAME, null, null);
}
/**
* readlogInformation :- Read the whole table
*
*/
public String[] readlogInformation() {
// Create string array of appropriate length
String[] returnArray;
// Retrieve preferences
SharedPreferences SqliteLogPref = thisContext.getSharedPreferences(PREFERENCE_NAME, 0);
int logNumber = SqliteLogPref.getInt("logNumber", 0);
// Open database for reading
DatabaseHelper databaseHelper = new DatabaseHelper(thisContext);
try {
SQLiteDatabase sQLiteDatabase = databaseHelper.getReadableDatabase();
// Get a cursor to the correct cell
Cursor cursor = sQLiteDatabase.query(TABLE_NAME, null, null, null, null, null, null);
// Get number of rows in table
int lengthOfTable = 0;
// Move cursor to where it needs to be
if (cursor != null) {
lengthOfTable = cursor.getCount();
// If count is less than max, then we have not wrapped around yet
if(lengthOfTable < TABLE_SIZE) {
cursor.moveToFirst();
}
// Position cursor appropriately
else {
cursor.moveToPosition(logNumber-1);
}
// Create string array of appropriate length
returnArray = new String[lengthOfTable];
for(int i=1; i<=lengthOfTable; i++) {
returnArray[i] = cursor.getString(1) + "; " + cursor.getString(2) + "; " + cursor.getString(3);
}
}
else {
Log.e(tag,"Cursor null");
// Create string array of appropriate length
returnArray = new String[0];
}
} catch(SQLiteException e) {
Log.d(tag,"SQLiteException when using getReadableDatabase");
// Create string array of appropriate length
returnArray = new String[0];
}
// Close database
databaseHelper.close();
return returnArray;
}
/**
* readlogInformation :- Read the whole table
*
*/
public String getTime() {
// Create a new time object
Time currentTime = new Time(Time.getCurrentTimezone());
// Get current time
currentTime.setToNow();
return currentTime.toString();
}
/**
* DatabaseHelper
*
*
* Class to help control database
*
*
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
/**
* <p>Constructor for DatabaseHelper
* @param context :- Context of calling class<p>
*
*/
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.d(tag,"DatabaseHelper constructor called");
}
/**
* <p>onCreate
* @param db :- Pass an sqlite object
*
*/
@Override
public void onCreate(SQLiteDatabase db) {
Log.d(tag,"onCreate called");
// Create database
db.execSQL(DATABASE_CREATE);
// Insert a new row
ContentValues values = new ContentValues();
// Create a certain number of rows
for(int i=1; i<=TABLE_SIZE; i++) {
values.clear();
values.put(COLUMN_LOGNUMBER, i);
values.put(COLUMN_FUNCTION, "empty");
values.put(COLUMN_DESCRIPTION, "empty");
db.insert(TABLE_NAME, "null", values);
}
Log.d(tag,"database created");
}
/**
* <p>onUpgrade
* @param db :- Pass an sqlite object
* @param oldVersion :- Old version of table
* @param newVersion :- New version of table
*
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(tag,"onUpgrade called");
// Not used, but you could upgrade the database with ALTER
// Scripts
}
}
}
I have been trying to figure this out for a while now. I would appreciate any insight, Amish

[Q] How to stop the ball at touch release

hi, its killing me i can't fix it i made this thing because i was learning Canvas and drawing on android !
i included moving animations (smooth) but i removed it
Code:
package com.example.graphics;
import android.content.Context;
import android.view.KeyEvent;
import android.view.MotionEvent;
import java.util.Formatter;
import android.graphics.Typeface;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.view.View;
public class BouncingBallView extends View {
private int xMin = 0; // This view's bounds
private int xMax;
private int yMin = 0;
private int yMax;
private float ballRadius = 80; // Ball's radius
private float ballX = ballRadius + 20; // Ball's center (x,y)
private float ballY = ballRadius + 40;
private float ballSpeedX = 11; // Ball's speed (x,y)
private float ballSpeedY = 7;
//private RectF ballBounds; // Needed for Canvas.drawOval
private Paint paint; // The paint (e.g. style, color) used for drawing
// Status message to show Ball's (x,y) position and speed.
private StringBuilder statusMsg = new StringBuilder();
private Formatter formatter = new Formatter(statusMsg); // Formatting the statusMsg
private float previousX;
private float previousY;
private float currentX;
private float currentY;
private float scale;
private int ifdrawcount = 0;
// Constructor
public BouncingBallView(Context context) {
super(context);
//ballBounds = new RectF();
paint = new Paint();
paint.setTypeface(Typeface.MONOSPACE);
paint.setTextSize(25);
setFocusableInTouchMode(true);
//setFocusable(true);
requestFocus();
}
/*public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_RIGHT: // Increase rightward speed
ballSpeedX++;
break;
case KeyEvent.KEYCODE_DPAD_LEFT: // Increase leftward speed
ballSpeedX--;
break;
case KeyEvent.KEYCODE_DPAD_UP: // Increase upward speed
ballSpeedY--;
break;
case KeyEvent.KEYCODE_DPAD_DOWN: // Increase downward speed
ballSpeedY++;
break;
case KeyEvent.KEYCODE_DPAD_CENTER: // Stop
ballSpeedX = 0;
ballSpeedY = 0;
break;
case KeyEvent.KEYCODE_A: // Zoom in
// Max radius is about 90% of half of the smaller dimension
float maxRadius = (xMax > yMax) ? yMax / 2 * 0.9f : xMax / 2 * 0.9f;
if (ballRadius < maxRadius) {
ballRadius *= 1.05; // Increase radius by 5%
}
break;
case KeyEvent.KEYCODE_Z: // Zoom out
if (ballRadius > 20) { // Minimum radius
ballRadius *= 0.95; // Decrease radius by 5%
}
break;
}
return true; // Event handled
}*/
// Called back to draw the view. Also called by invalidate().
@Override
protected void onDraw(Canvas canvas) {
// Draw the ball
//ballBounds.set(ballX-ballRadius, ballY-ballRadius, ballX+ballRadius, ballY+ballRadius);
//paint.setColor(Color.GRAY);
//canvas.drawOval(ballBounds, paint);
//canvas.drawCircle(70, yMax -70, 60, paint);
//canvas.drawCircle(xMax -70, yMax -60, 60, paint);
paint.setColor(Color.GREEN);
canvas.drawCircle(ballX, ballY, ballRadius, paint);
// Draw the status message
paint.setColor(Color.WHITE);
paint.setStrokeWidth(2);
canvas.drawText(statusMsg.toString(), 10, 30, paint);
if(ifdrawcount > 0){
canvas.drawLine(previousX, previousY, currentX, currentY, paint);
paint.setStrokeWidth(10);
paint.setColor(Color.BLACK);
canvas.drawPoint(previousX,previousY,paint);
ifdrawcount--;
}
// Update the position of the ball, including collision detection and reaction.
update();
// Delay
try {
Thread.sleep(16);
} catch (InterruptedException e) { }
invalidate(); // Force a re-draw
}
// Touch-input handler
@Override
public boolean onTouchEvent(MotionEvent event) {
currentX = event.getX();
currentY = event.getY();
ifdrawcount = 10;
//float deltaX, deltaY;
scale = 20.0f / ((xMax > yMax) ? yMax : xMax);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
previousX = currentX;
previousY = currentY;
case MotionEvent.ACTION_MOVE:
ballSpeedY = (currentY - previousY) * scale;
ballSpeedX = (currentX - previousX) * scale;
case MotionEvent.ACTION_UP:
ballSpeedX = 0;
ballSpeedY = 0;
}
return true; // Event handled
}
// Detect collision and update the position of the ball.
private void update() {
// Get new (x,y) position
ballX += ballSpeedX;
ballY += ballSpeedY;
/*if(ifdrawcount == 0)
ballSpeedX = 0; ballSpeedY = 0;*/
// Detect collision and react
if (ballX + ballRadius > xMax) {
ballSpeedX = -ballSpeedX;
ballX = xMax-ballRadius;
} else if (ballX - ballRadius < xMin) {
ballSpeedX = -ballSpeedX;
ballX = xMin+ballRadius;
}
if (ballY + ballRadius > yMax) {
ballSpeedY = -ballSpeedY;
ballY = yMax - ballRadius;
} else if (ballY - ballRadius < yMin) {
ballSpeedY = -ballSpeedY;
ballY = yMin + ballRadius;
}
// Build status message
statusMsg.delete(0, statusMsg.length()); // Empty buffer
formatter.format("%3.0f %3.0f || %3.0f %3.0f", ballSpeedX, ballSpeedY,ballX,ballY);
}
// Called back when the view is first created or its size changes.
@Override
public void onSizeChanged(int w, int h, int oldW, int oldH) {
// Set the movement bounds for the ball
xMax = w-1;
yMax = h-1;
}
}
the problem is my ball doesn't move at all, but i see the line, once i remove the line:
Code:
case MotionEvent.ACTION_UP:
ballSpeedX = 0;
ballSpeedY = 0;
it works, but you know, after release it continues with same speed :! its like the ACTION_UP is always the case, !!! any idea why it doesn't work, how to stop the ball once the user releases the screen?
also sorry if this is not the right place. i searched the forums, i got confused i didn't find anyplace to ask this question so i tough this is the best place!

Java is too complex for begginer lovers

I love Android. I want to learn to develop apps. I keep reading tutorials. I got dissapointed and read about HTML frameworks (phonegap, etc). I came back to Android Native Java. I want to learn from the roots. However, some things discourages me....
All this part of the code is just for making a request to the Openweather API and get the json data (plus a little debugging stuff); which in Python or similar languages you only have to care about
- importing the library that handles http requests
- make the request in one function and save it into a json object
Code:
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
String format = "json";
String units = "metric";
int numDays = 7;
try {
final String FORECAST_BASE_URL =
"<the-domain>/data/2.5/forecast/daily?";
final String QUERY_PARAM = "q";
final String FORMAT_PARAM = "mode";
final String UNITS_PARAM = "units";
final String DAYS_PARAM = "cnt";
Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
.appendQueryParameter(QUERY_PARAM, params[0])
.appendQueryParameter(FORMAT_PARAM, format)
.appendQueryParameter(UNITS_PARAM, units)
.appendQueryParameter(DAYS_PARAM, Integer.toString(numDays))
.build();
URL url = new URL(builtUri.toString());
Log.v(LOG_TAG, "Built URI " + builtUri.toString());
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
forecastJsonStr = buffer.toString();
Log.v(LOG_TAG, "Forecast string: " + forecastJsonStr);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
This is the complete Class:
Code:
public class FetchWeatherTask extends AsyncTask<String, Void, String[]> {
private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();
/* The date/time conversion code is going to be moved outside the asynctask later,
* so for convenience we're breaking it out into its own method now.
*/
private String getReadableDateString(long time){
// Because the API returns a unix timestamp (measured in seconds),
// it must be converted to milliseconds in order to be converted to valid date.
Date date = new Date(time * 1000);
SimpleDateFormat format = new SimpleDateFormat("E, MMM d");
return format.format(date).toString();
}
/**
* Prepare the weather high/lows for presentation.
*/
private String formatHighLows(double high, double low) {
// For presentation, assume the user doesn't care about tenths of a degree.
long roundedHigh = Math.round(high);
long roundedLow = Math.round(low);
String highLowStr = roundedHigh + "/" + roundedLow;
return highLowStr;
}
/**
* Take the String representing the complete forecast in JSON Format and
* pull out the data we need to construct the Strings needed for the wireframes.
*
* Fortunately parsing is easy: constructor takes the JSON string and converts it
* into an Object hierarchy for us.
*/
private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays)
throws JSONException {
// These are the names of the JSON objects that need to be extracted.
final String OWM_LIST = "list";
final String OWM_WEATHER = "weather";
final String OWM_TEMPERATURE = "temp";
final String OWM_MAX = "max";
final String OWM_MIN = "min";
final String OWM_DATETIME = "dt";
final String OWM_DESCRIPTION = "main";
JSONObject forecastJson = new JSONObject(forecastJsonStr);
JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);
String[] resultStrs = new String[numDays];
for(int i = 0; i < weatherArray.length(); i++) {
// For now, using the format "Day, description, hi/low"
String day;
String description;
String highAndLow;
// Get the JSON object representing the day
JSONObject dayForecast = weatherArray.getJSONObject(i);
// The date/time is returned as a long. We need to convert that
// into something human-readable, since most people won't read "1400356800" as
// "this saturday".
long dateTime = dayForecast.getLong(OWM_DATETIME);
day = getReadableDateString(dateTime);
// description is in a child array called "weather", which is 1 element long.
JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
description = weatherObject.getString(OWM_DESCRIPTION);
// Temperatures are in a child object called "temp". Try not to name variables
// "temp" when working with temperature. It confuses everybody.
JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
double high = temperatureObject.getDouble(OWM_MAX);
double low = temperatureObject.getDouble(OWM_MIN);
highAndLow = formatHighLows(high, low);
resultStrs[i] = day + " - " + description + " - " + highAndLow;
}
for (String s : resultStrs) {
Log.v(LOG_TAG, "Forecast entry: " + s);
}
return resultStrs;
}
@Override
protected String[] doInBackground(String... params) {
// If there's no zip code, there's nothing to look up. Verify size of params.
if (params.length == 0) {
return null;
}
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
String format = "json";
String units = "metric";
int numDays = 7;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page
final String FORECAST_BASE_URL =
"<the-domain>/data/2.5/forecast/daily?";
final String QUERY_PARAM = "q";
final String FORMAT_PARAM = "mode";
final String UNITS_PARAM = "units";
final String DAYS_PARAM = "cnt";
Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
.appendQueryParameter(QUERY_PARAM, params[0])
.appendQueryParameter(FORMAT_PARAM, format)
.appendQueryParameter(UNITS_PARAM, units)
.appendQueryParameter(DAYS_PARAM, Integer.toString(numDays))
.build();
URL url = new URL(builtUri.toString());
Log.v(LOG_TAG, "Built URI " + builtUri.toString());
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
forecastJsonStr = buffer.toString();
Log.v(LOG_TAG, "Forecast string: " + forecastJsonStr);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
try {
return getWeatherDataFromJson(forecastJsonStr, numDays);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
// This will only happen if there was an error getting or parsing the forecast.
return null;
}
}
I mean, I know this code can be reduced, but I'm angry about the way it works. Everything needs to be passed to another object! And even rembember all those castings! Castings everywhere!
- The builded URI to the URL.
- The URL to the HttpConection variable.
- Once you connect, save that into the InputStream.
- Make a StringBuffer because we are going to send line by line everything.
- Then create the reader = new BufferedReader(new InputStreamReader(inputStream)).
- Append the lines to the buffer and return if it's ok.
- Else catch all the errors and be sure to close all the connections.
Damn Java !
Forgive me. You'll hate me.
Java is readable, that's the truth... but don't tell me that it is easy for a normal person.
Am I the only one?
If you are a beginner and will straight move to these classes. You will obviously find Java difficult. But Java is very easy if you move step by step from start
Sent from my XT1033 using XDA Premium 4 mobile app
---------- Post added at 04:18 PM ---------- Previous post was at 04:16 PM ----------
And that library also does the same thing inside. Only difference is, your work is already done by author of the library.
Sent from my XT1033 using XDA Premium 4 mobile app
Java is definitely a very verbose language but it's also widely used and so you will find many libraries that do tasks like grab JSON data from a service that have already been implemented for you
manwoman said:
Damn Java !
Forgive me. You'll hate me.
Java is readable, that's the truth... but don't tell me that it is easy for a normal person.
Am I the only one?
Click to expand...
Click to collapse
I don't think you're the only one. It's easy to get scared away by the many too verbose examples available, the key is to look at what you're trying to achieve and then break it up into those parts.
Your code listing is (I think) an attempt to show all steps to get the forecast data, but if that would have been broken up into smaller steps I don't think you'd look at it as quite as bad.
You would then have methods like
Code:
URL getForecastUrl(String parameter);
Code:
BufferedReader getUrl(URL url) { }
Code:
String readAll(BufferedReader reader) {}
Each of which would have had something like 6-7 lines of simple, cohesive code.
I understand your point, but in this particular scenario I think you're the victim of a poorly structured code sample rather than a too verbose language.
If you think the default implementation is too complicated, here are also many java libraries which will make your life easier.

Starting chronometer with if condition comparing strings

I have an android application that is receiving a string from an arduino via Bluetooth, names the string "data" and displays it by setting a TextView to the string "data". I want a chronometer to start when the incoming string matches a predefined string.
For example:
Code:
if data.equals(startChrono)){
chronometerLeft.setBase(SystemClock.elapsedRealtime());
chronometerLeft.start();
I actually have the arduino sending a "g" and am setting my string goL to be "g" but cannot get the chronometer to start when the g is received. My TextView shows the g. Code is below. I've tried several things and at a loss. Using same code for chronometer.start() with onClickListener with a button works great. I just need it to start the chronometer when i receive a specific string from the arduino.
Code:
beginListenForData();
// text.setText("Bluetooth Opened");
}
void beginListenForData() {
final Handler handler = new Handler();
final byte delimiter = 10; // This is the ASCII code for a newline
// character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable() {
public void run() {
while (!Thread.currentThread().isInterrupted() && !stopWorker) {
try {
int bytesAvailable = mmInputStream.available();
if (bytesAvailable > 0) {
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for (int i = 0; i < bytesAvailable; i++) {
byte b = packetBytes[i];
if (b == delimiter) {
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0,
encodedBytes, 0,
encodedBytes.length);
final String data = new String(
encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable() {
public void run() {
text.setText(data);
String goL = "g";
String goR = "f";
chronometerLeft = (Chronometer)findViewById(R.id.chronometerLeft);
chronometerRight = (Chronometer)findViewById(R.id.chronometerRight);
if(data.equals(goL)){
chronometerLeft.setBase(SystemClock.elapsedRealtime());
chronometerLeft.start();
if(data.equals(goR))
chronometerRight.setBase(SystemClock.elapsedRealtime());
chronometerRight.start();
}
}
});
} else {
readBuffer[readBufferPosition++] = b;
}
}
}
} catch (IOException ex) {
stopWorker = true;
}
}
}
});
workerThread.start();
}
Sorry to bother, but in your while loop condition, what does the '!' before Thread do?

How to draw or erase on a photo loaded onto a Imageview?

As what was stated on the header I want to implement either a "paint" function for user to edit paint/censor unwanted parts of a photo displayed on a imageview before uploading it to a server in the edited format and a redo function if user makes a mistake while editing?
How do I come about doing it, I've read relevant topics on Canvas, or FingerPaint but still puzzled on how to implement it based on my project here? Tried referencing to the links here and here but without success in implementing the codes into my project code due to my lack of programming skills.
Thanks for any help rendered!
Tried integrating the codes below into my code above (image preview after taking a photo with the camera) for user to start editing via painting but still not working? Thanks for any help rendered!
Code:
public class Drawing extends View {
private Paint mPaint, mBitmapPaint;
Intent intent = getIntent();
Bitmap mBitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");
private Canvas mCanvas;
private Path mPath;
private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;
private int color, size, state;
private ArrayList<Path> paths = new ArrayList<Path>();
private ArrayList<Path> undonePaths = new ArrayList<Path>();
private ArrayList<Integer> colors = new ArrayList<Integer>();
private ArrayList<Integer> sizes = new ArrayList<Integer>();
public Drawing(Context c) {
super(c);
}
public Drawing(Context c,int width, int height, int size, int color, int state) {
super(c);
mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
mPath = new Path();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
// mBitmapPaint = new Paint(Paint.DITHER_FLAG);
// mBitmapPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
setColor(color);
setSize(size);
setState(state);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}
@Override
protected void onDraw(Canvas canvas) {
// canvas.drawColor(Color.TRANSPARENT);
// canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
//
// if (state == 0)
// mBitmap.eraseColor(Color.TRANSPARENT);
for (int i = 0; i < paths.size(); i++) {
mPaint.setColor(colors.get(i));
mPaint.setStrokeWidth(sizes.get(i));
canvas.drawPath(paths.get(i), mPaint);
}
mPaint.setColor(color);
mPaint.setStrokeWidth(size);
canvas.drawPath(mPath, mPaint);
}
public void setColor(int color) {
this.color = color;
}
public void setSize(int size) {
this.size = size;
}
public void setState(int state) {
this.state = state;
// if (state == 0)
// mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
// else
// mPaint.setXfermode(null);
}
public void onClickUndo() {
if (paths.size() > 0) {
undonePaths.add(paths.remove(paths.size() - 1));
sizes.remove(sizes.size() - 1);
colors.remove(colors.size() - 1);
invalidate();
}
}
private void touch_start(float x, float y) {
undonePaths.clear();
mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
}
private void touch_move(float x, float y) {
float dx = Math.abs(x - mX);
float dy = Math.abs(y - mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
mX = x;
mY = y;
}
}
private void touch_up() {
mPath.lineTo(mX, mY);
mCanvas.drawPath(mPath, mPaint);
colors.add(color);
sizes.add(size);
paths.add(mPath);
mPath = new Path();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touch_start(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
break;
}
return true;
}
}

Categories

Resources