Android widget get touch position - android

is it possible to get the position of a touch when the user touches my widget on the homescreen? TIA
edit: my widget code:
public class MyWidgetProvider extends AppWidgetProvider {
public static String ACTION_WIDGET_MEMO = "comNgarsideMemoActionWidgetMemo";
public static String ACTION_WIDGET_PEN = "comNgarsideMemoActionWidgetPen";
public static String ACTION_WIDGET_ERASER = "comNgarsideMemoActionWidgetEraser";
public static String ACTION_WIDGET_UNDO = "comNgarsideMemoActionWidgetUndo";
public static String ACTION_WIDGET_REDO = "comNgarsideMemoActionWidgetRedo";
public static String ACTION_WIDGET_SAVE = "comNgarsideMemoActionWidgetSave";
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
Intent memoIntent = new Intent(context, ListActivity.class);
memoIntent.setAction(ACTION_WIDGET_MEMO);
Intent penIntent = new Intent(context, MyWidgetProvider.class);
penIntent.setAction(ACTION_WIDGET_PEN);
Intent eraserIntent = new Intent(context, MyWidgetProvider.class);
eraserIntent.setAction(ACTION_WIDGET_ERASER);
Intent undoIntent = new Intent(context, MyWidgetProvider.class);
undoIntent.setAction(ACTION_WIDGET_UNDO);
Intent redoIntent = new Intent(context, MyWidgetProvider.class);
redoIntent.setAction(ACTION_WIDGET_REDO);
Intent saveIntent = new Intent(context, MyWidgetProvider.class);
saveIntent.setAction(ACTION_WIDGET_SAVE);
PendingIntent memoPendingIntent = PendingIntent.getActivity(context, 0, memoIntent, 0);
PendingIntent penPendingIntent = PendingIntent.getBroadcast(context, 0, penIntent, 0);
PendingIntent eraserPendingIntent = PendingIntent.getBroadcast(context, 0, eraserIntent, 0);
PendingIntent undoPendingIntent = PendingIntent.getBroadcast(context, 0, undoIntent, 0);
PendingIntent redoPendingIntent = PendingIntent.getBroadcast(context, 0, redoIntent, 0);
PendingIntent savePendingIntent = PendingIntent.getBroadcast(context, 0, saveIntent, 0);
remoteViews.setOnClickPendingIntent(R.id.iconBtn, memoPendingIntent);
remoteViews.setOnClickPendingIntent(R.id.penBtn, penPendingIntent);
remoteViews.setOnClickPendingIntent(R.id.eraserBtn, eraserPendingIntent);
remoteViews.setOnClickPendingIntent(R.id.undoBtn, undoPendingIntent);
remoteViews.setOnClickPendingIntent(R.id.redoBtn, redoPendingIntent);
remoteViews.setOnClickPendingIntent(R.id.saveBtn, savePendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
}
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
final int appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
this.onDeleted(context, new int[] { appWidgetId });
}
} else {
if (intent.getAction().equals(ACTION_WIDGET_PEN)) {
} else if (intent.getAction().equals(ACTION_WIDGET_ERASER)) {
} else if (intent.getAction().equals(ACTION_WIDGET_UNDO)) {
} else if (intent.getAction().equals(ACTION_WIDGET_REDO)) {
} else if (intent.getAction().equals(ACTION_WIDGET_SAVE)) {
}
super.onReceive(context, intent);
}
}
}

Maybe this will give you an idea...
PressureDynamics.java
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.content.Context;
import android.util.Log;
/**
* Keyboard sensor
*/
public class PressureDynamics extends Thread implements FeatureExtractor{
public static final String AVG_TOUCH_PRESSURE = "Avg_Touch_Pressure";
public static final String AVG_TOUCH_AREA = "Avg_Touch_Area";
private static final int EVENT_BYTE_SIZE = 16;
private InputStream _fis = null;
private boolean _shouldRun;
private Map<String, TouchScreenSensor> _sensors;
public PressureDynamics(Context context, Collection<FeatureInfo> featureInfos,
Long timeStamp){
super("Pressure Dynamics Feature Extractor Thread");
_shouldRun = true;
_sensors = new HashMap<String, TouchScreenSensor>();
int featureCount = 0;
for (FeatureInfo featureInfo : featureInfos){
String name = featureInfo.name;
try{
if (name.equalsIgnoreCase(AVG_TOUCH_PRESSURE)){
TouchScreenSensor s = new AvgTouchPressureSensor(featureInfo);
_sensors.put(AVG_TOUCH_PRESSURE, s);
}else if (name.equalsIgnoreCase(AVG_TOUCH_AREA)){
TouchScreenSensor s = new AvgTouchAreaSensor(featureInfo);
_sensors.put(AVG_TOUCH_AREA, s);
}else{
Log.e(FE_TAG, "Unhandled feature by " + getClass().getCanonicalName()
+ ": " + name);
continue;
}
++featureCount;
}catch(RuntimeException e){
Log.e(FE_TAG, "Unable to initialize feature: " + name, e);
}
}
if (featureCount == 0){
throw new FeatureExtractorInitException("No features of "
+ getClass().getCanonicalName() + " could be initialized");
}
_fis = openTouchScreenInputStream();
start();
}
private static InputStream openTouchScreenInputStream(){
final String HTC_TOUCH_SCREEN_INPUT_FILEPATH = "/dev/input/event1";
LocalServerConn localServerConn;
try{
localServerConn = LocalServerConn.getInstance();
localServerConn.runLocalServer();
}catch(Exception e){
throw new FeatureExtractorInitException(
"Unable to collect Touch Screen features", e);
}
try{
FileDescriptor[] fdArr = localServerConn
.sendFileDescriptorReq(HTC_TOUCH_SCREEN_INPUT_FILEPATH);
if (fdArr == null || fdArr.length == 0){
throw new FeatureExtractorInitException("Can't open keyboard device");
}
return new FileInputStream(fdArr[0]);
}catch(IOException e){
throw new FeatureExtractorInitException("Can't open keyboard input stream: "
+ e.getMessage(), e);
}
}
public void close(){
_shouldRun = false;
}
public void collectData(List<MonitoredData> monitoredData, ParcelableDate endTime){
for (Sensor s : _sensors.values()){
s.collectData(monitoredData, endTime);
}
}
public void run(){
int n;
int pos = 0;
byte[] buffer = new byte[256];
for (;;){
try{
n = _fis.read(buffer, pos, EVENT_BYTE_SIZE);
/*
* check if we are shutting down - this may have the thread hanging around
* until the next touch event comes in
*/
if (_shouldRun == false){
break;
}
pos += n;
// Log.v(FE_TAG, "read touch screen event: " + n + " bytes\n");
if (pos >= EVENT_BYTE_SIZE){
long currentTimeMillis = System.currentTimeMillis();
TouchEvent touchScreenEvent = new TouchEvent(buffer,
currentTimeMillis);
updateSensors(touchScreenEvent, currentTimeMillis);
pos -= EVENT_BYTE_SIZE;
}
}catch(IOException e){
Log.e(FE_TAG, e.getMessage(), e);
}
}
}
private void updateSensors(TouchEvent touchScreenEvent, long currentTimeMillis){
try{
// currently filter out all non preassure event types
//
switch ((int)touchScreenEvent.getCode()){
case TouchEvent.X_POS_EVENT:
case TouchEvent.Y_POS_EVENT:
case TouchEvent.TOUCH_DEVICE_TYPE_EVENT:
break;
case TouchEvent.ABS_PRESSURE_EVENT:
_sensors.get(AVG_TOUCH_PRESSURE).updateSensor(touchScreenEvent,
currentTimeMillis);
break;
case TouchEvent.ABS_TOOL_WIDTH_EVENT:
_sensors.get(AVG_TOUCH_AREA).updateSensor(touchScreenEvent,
currentTimeMillis);
break;
default:
Log.e(FE_TAG, "unrecognized touch event code :"
+ touchScreenEvent.getCode());
break;
}
}catch(Exception e){
Log.e(FE_TAG, e.getMessage(), e);
}
}
public String toString(){
return getClass().getSimpleName();
}
private static abstract class TouchScreenSensor extends Sensor{
private TouchScreenSensor(String name, FeatureInfo info){
//super(name, info.getValueTimeout());
super(name);
}
public abstract void updateSensor(TouchEvent event, long currentTimeMillis);
}
private static class AvgTouchPressureSensor extends TouchScreenSensor{
public AvgTouchPressureSensor(FeatureInfo info){
super(AVG_TOUCH_PRESSURE, info);
}
public void updateSensor(TouchEvent event, long currentTimeMillis){
addToAvg(event.getValue(), currentTimeMillis);
}
}
private static class AvgTouchAreaSensor extends TouchScreenSensor{
public AvgTouchAreaSensor(FeatureInfo info){
super(AVG_TOUCH_AREA, info);
}
public void updateSensor(TouchEvent event, long currentTimeMillis){
addToAvg(event.getValue(), currentTimeMillis);
}
}
}
Sensor.java
import java.util.List;
public class Sensor{
private final String _name;
private Double _avg;
private int _count;
private long _lastValueUpdateTime;
/**
* Constructor
*
* #param name The name of the feature that is collected by this sensor
* #param valueTimeout The time period of no value changes it takes for the current
* value to reset to the initial value (in millis)
*/
public Sensor(String name){
_lastValueUpdateTime = 0;
_name = name;
_avg = null;
_count = 0;
}
public void collectData(List<MonitoredData> monitoredData, ParcelableDate endTime){
Double value = getValue(endTime.getTime());
if (value != null){
value = Utils.truncateDouble(value);
}
monitoredData.add(new MonitoredData(_name, value, endTime));
}
public Double getValue(long time){
if (time - _lastValueUpdateTime > MainActivity.getAgentLoopTime()){
_avg = null;
_count = 0;
}
return _avg;
}
public String getName(){
return _name;
}
public void addToAvg(double value, long time){
Double avg = getValue(time);
if (avg == null){
avg = value; // Initial value
}else{
value = (avg * _count + value) / (_count + 1);
}
++_count;
_avg = value;
_lastValueUpdateTime = time;
}
#Override
public String toString(){
return _name;
}
}
TouchEvent.java
import android.util.Log;
import dt.util.Utils;
public class TouchEvent{
public static final int ABS_PRESSURE_EVENT = 0x18;
public static final int ABS_TOOL_WIDTH_EVENT = 0x1c;
public static final int X_POS_EVENT = 0x0;
public static final int Y_POS_EVENT = 0x1;
/* type of touching device ie. finger, stylus etc. */
public static final int TOUCH_DEVICE_TYPE_EVENT = 0x14a;
// private final long _timeStamp;
// private final int _sec;
// private final int _usec;
// 3, 1, 0 - ?
// private final long _type;
// different event types have different codes
private final long _code;
private final int _value;
//
public TouchEvent(byte[] _buffer, long currentTimeMillis){
int pos;
byte b[] = new byte[4];
byte s[] = new byte[2];
// _timeStamp = currentTimeMillis;
pos = 0;
// _sec = Utils.LittleEndianBytesToInt(_buffer);
pos += 4;
System.arraycopy(_buffer, pos, b, 0, 4);
// _usec = Utils.LittleEndianBytesToInt(b);
pos += 4;
// _type = Utils.LittleEndianBytesToUShort(s);
pos += 2;
System.arraycopy(_buffer, pos, s, 0, 2);
_code = Utils.littleEndianBytesToUShort(s);
pos += 2;
System.arraycopy(_buffer, pos, b, 0, 4);
_value = Utils.littleEndianBytesToInt(b);
if (_code != X_POS_EVENT && _code != Y_POS_EVENT
&& _code != TOUCH_DEVICE_TYPE_EVENT && _code != ABS_PRESSURE_EVENT
&& _code != ABS_TOOL_WIDTH_EVENT){
Log.d(FE_TAG, "unrecognized touch event code :" + _code);
}
}
public long getCode(){
return _code;
}
public double getValue(){
return _value;
}
}
FeatureInfo.java
import java.util.HashMap;
public class FeatureInfo{
/** The name of the feature */
public final String name;
/** The parameters relevant to the feature */
public final HashMap<String, String> params;
/**
* Constructs a FeatureInfo object from the given parameters
*
* #param name The name of the feature
* #param params The parameters relevant to the feature
*/
public FeatureInfo(String name, HashMap<String, String> params){
this.name = name;
this.params = (params == null) ? new HashMap<String, String>() : params;
}
#Override
public String toString(){
return name;
}
public int getTimeWindow() throws IllegalArgumentException{
final String paramName = "Time_Window";
try{
int timeWindow = Integer.parseInt(params.get(paramName)) * 1000;
if (timeWindow <= 0){
throw new IllegalArgumentException("Must be a positive integer");
}
return timeWindow;
}catch(Exception e){// NullPointer or Parsing
throw new IllegalArgumentException("Corrupt parameter: " + paramName
+ " in feature " + name, e);
}
}
// public int getTimeWindow() throws IllegalArgumentException{
// final String paramName = "Time_Window";
// try{
// int timeWindow = Integer.parseInt(params.get(paramName)) * 1000;
// if (timeWindow <= 0){
// throw new IllegalArgumentException("Must be a positive integer");
// }
// return timeWindow;
// }catch(Exception e){// NullPointer or Parsing
// throw new IllegalArgumentException("Corrupt parameter: " + paramName
// + " in feature " + name, e);
// }
// }
public int getValueTimeout() throws IllegalArgumentException{
final String paramName = "Value_Timeout";
try{
int valueTimeout = Integer.parseInt(params.get(paramName)) * 1000;
if (valueTimeout <= 0){
throw new IllegalArgumentException("Must be a positive integer");
}
return valueTimeout;
}catch(Exception e){// NullPointer or Parsing
throw new IllegalArgumentException("Corrupt parameter: " + paramName
+ " in feature " + name, e);
}
}
public double getMovieAverageWeight() throws IllegalArgumentException{
final String paramName = "Moving_Average_Weight";
try{
double movingAverageWeight = Double.parseDouble(params.get(paramName));
if (movingAverageWeight < 0 || movingAverageWeight > 1){
throw new IllegalArgumentException("Must be positive and 1.0 at most");
}
return movingAverageWeight;
}catch(Exception e){// NullPointer or Parsing
throw new IllegalArgumentException("Corrupt parameter: " + paramName
+ " in feature " + name, e);
}
}
public boolean getIncludeEventTimes(){
final String paramName = "Include_Event_Times";
return Boolean.parseBoolean(params
.get(paramName));
}
public boolean getIncludeMaximalEntity(){
final String paramName = "Include_Maximal_Entity";
return Boolean.parseBoolean(params
.get(paramName));
}
}
MonitoredData.java
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
#SuppressWarnings("unchecked")
public class MonitoredData implements Map, Parcelable{
public static final int DEFAULT = 0;
public static final int HAS_EXTRAS = 1;
protected String _name;
protected ParcelableDate _startTime, _endTime;
protected Object _value;
protected Bundle _extras;
public static final Parcelable.Creator<MonitoredData> CREATOR = new Parcelable.Creator<MonitoredData>(){
public MonitoredData createFromParcel(Parcel in){
ClassLoader cl = ParcelableDate.class.getClassLoader();
String name = in.readString();
Object value = in.readValue(null);
ParcelableDate startTime = (ParcelableDate)in.readParcelable(cl);
ParcelableDate endTime = (ParcelableDate)in.readParcelable(cl);
Bundle extras = in.readBundle();
MonitoredData monitoredData = new MonitoredData(name, value, startTime,
endTime);
if (extras != null){
monitoredData.setExtras(extras);
}
return monitoredData;
}
public MonitoredData[] newArray(int size){
return new MonitoredData[size];
}
};
private static DateFormat _sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
public MonitoredData(String name, Object value, Date endTime){
this(name, value, new ParcelableDate(endTime), new ParcelableDate(endTime));
}
public MonitoredData(String name, Object value, ParcelableDate endTime){
this(name, value, endTime, endTime);
}
public MonitoredData(String name, Object value, Date startTime, Date endTime){
this(name, value, new ParcelableDate(startTime), new ParcelableDate(endTime));
}
public MonitoredData(String name, Object value, Date startTime, ParcelableDate endTime){
this(name, value, new ParcelableDate(startTime), endTime);
}
public MonitoredData(String name, Object value, ParcelableDate startTime,
ParcelableDate endTime){
_name = name;
_startTime = startTime;
_endTime = endTime;
_value = value;
_extras = null;
}
public void setExtras(Bundle extras){
_extras = extras;
}
public Map<String, Object> toMap(){
TreeMap<String, Object> map = new TreeMap<String, Object>();
map.put("Name", _name);
map.put("StartTime", _startTime);
map.put("EndTime", _endTime);
map.put("Value", _value);
return map;
}
public String conciseToString(){
String extrasToString = (_extras != null && !_extras.isEmpty()) ? " - "
+ _extras.toString() : "";
return "{" + getName() + " = " + getValue() + "}" + extrasToString;
}
public int describeContents(){
return (_extras == null || _extras.isEmpty()) ? DEFAULT : HAS_EXTRAS;
}
public ParcelableDate getEndTime(){
return _endTime;
}
public String getName(){
return _name;
}
public ParcelableDate getStartTime(){
return _startTime;
}
public Object getValue(){
return _value;
}
public Bundle getExtras(){
return _extras;
}
public String toString(){
StringBuilder sb = new StringBuilder("{");
sb.append("Name = " + getName() + ", ");
sb.append("Value = " + getValue() + ", ");
sb.append("StartTime = " + _sdf.format(getStartTime()) + ", ");
sb.append("EndTime = " + _sdf.format(getEndTime()));
sb.append("}");
return sb.toString();
}
public void writeToParcel(Parcel dest, int flags){
dest.writeString(getName());
dest.writeValue(getValue());
dest.writeParcelable(getStartTime(), 0);
dest.writeParcelable(getEndTime(), 0);
dest.writeBundle(_extras);
}
public void clear(){
throw new UnsupportedOperationException();
}
public boolean containsKey(Object key){
throw new UnsupportedOperationException();
}
public boolean containsValue(Object value){
throw new UnsupportedOperationException();
}
public Set entrySet(){
return Collections.unmodifiableSet(toMap().entrySet());
}
public Object get(Object key){
throw new UnsupportedOperationException();
}
public boolean isEmpty(){
throw new UnsupportedOperationException();
}
public Set keySet(){
throw new UnsupportedOperationException();
}
public Object put(Object key, Object value){
throw new UnsupportedOperationException();
}
public void putAll(Map arg0){
throw new UnsupportedOperationException();
}
public Object remove(Object key){
throw new UnsupportedOperationException();
}
public int size(){
throw new UnsupportedOperationException();
}
public Collection values(){
throw new UnsupportedOperationException();
}
/**
* Returns the value of the monitored data as a Double.
* Null is returned if the value is null or is can not be converted to double.
*
* #return The value as double if possible, null otherwise
*/
public Double mdToDouble(){
Double sample;
Object val = getValue();
if (val instanceof Double){
sample = ((Double)val).doubleValue();
}else if (val instanceof Long){
sample = ((Long)val).doubleValue();
}else if (val instanceof Integer){
sample = ((Integer)val).doubleValue();
}else{
sample = null;
}
return sample;
}
}
Utils.java
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Formatter;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.content.Context;
import android.content.res.Resources;
import android.os.Environment;
import android.widget.Toast;
public class Utils{
public static byte[] append(byte[] first, byte[] second){
byte[] bytes;
bytes = new byte[first.length + second.length];
System.arraycopy(first, 0, bytes, 0, first.length);
System.arraycopy(second, 0, bytes, first.length, second.length);
return bytes;
}
public static int bytesToInt(byte[] bytes){
return (bytes[3] & 0xFF) | ((bytes[2] & 0xFF) << 8) | ((bytes[1] & 0xFF) << 16)
| ((bytes[0] & 0xFF) << 24);
}
public static int littleEndianBytesToInt(byte[] bytes){
return (bytes[0] & 0xFF) | ((bytes[1] & 0xFF) << 8) | ((bytes[2] & 0xFF) << 16)
| ((bytes[3] & 0xFF) << 24);
}
public static long littleEndianBytesToUShort(byte[] arr){
return (arr[1] << 8) | arr[0];
}
public static void displayShortAlert(Context context, String message){
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
public static XmlPullParser getXPP(Context context, int resourceId, boolean isBinary){
XmlPullParser xpp;
Resources resources = context.getResources();
if (isBinary){
return resources.getXml(resourceId);
}else{
try{
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
xpp = factory.newPullParser();
xpp.setInput(resources.openRawResource(resourceId), null);
}catch(XmlPullParserException e){
xpp = null;
}
return xpp;
}
}
public static byte[] intToBytes(int i){
byte[] bytes = new byte[]{(byte)((i >> 24) & 0xff), (byte)((i >> 16) & 0xff),
(byte)((i >> 8) & 0xff), (byte)((i) & 0xff)};
return bytes;
}
/*
* debugging
*/
public static String printByteArray(byte[] bytes, int len){
StringBuilder sb = new StringBuilder();
sb.append("msg len: " + len + " :");
Formatter f = new Formatter(sb);
for (int i = 0; i < len; i++){
f.format("%2x", bytes[i]);
}
sb.append("\n");
return sb.toString();
}
public static List<Integer> getPids(String fileName){
String line;
int pidIndex = -1;
try{
Process p = Runtime.getRuntime().exec("ps " + fileName);
p.waitFor();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()), 256);
if ((line = br.readLine()) == null){
throw new IllegalStateException("Unable to read ps output");
}
String[] tokens = line.split(" +");
for (int i = 0; i < tokens.length; ++i){
if (tokens[i].equalsIgnoreCase("pid")){
pidIndex = i;
}
}
if (pidIndex < 0){
throw new IllegalStateException("Unable to locate pid field in ps output");
}
List<Integer> pids = new ArrayList<Integer>();
while ((line = br.readLine()) != null){
tokens = line.split(" +");
assert tokens.length < 9;
try{
pids.add(Integer.parseInt(tokens[pidIndex]));
}catch(NumberFormatException e){
throw new IllegalStateException("Pid is not an integer");
}
}
br.close();
return pids;
}catch(Exception e){
throw new IllegalStateException("Unable to read running process through ps: "
+ e.getMessage(), e);
}
}
public static void killProcesses(List<Integer> pids){
for (Integer pid : pids){
android.os.Process.killProcess(pid);
}
}
public static void killProcesses(String processName){
killProcesses(getPids(processName));
}
public static void suKillProcesses(List<Integer> pids){
StringBuilder cmd = new StringBuilder("kill");
for (Integer pid : pids){
cmd.append(" ").append(pid);
}
try{
Runtime.getRuntime().exec(new String[]{"su", "-c", cmd.toString()});
}catch(IOException e){
e.printStackTrace();
}
}
public static void suKillProcess(int pid){
try{
Runtime.getRuntime().exec(new String[]{"su", "-c", "kill " + pid});
}catch(IOException e){
e.printStackTrace();
}
}
public static void suKillProcesses(String processName){
suKillProcesses(getPids(processName));
}
public static double truncateDouble(double d){
long l = Math.round(d * 100);
return l / 100.0;
}
public static double calcMovingAvg(double oldVal, double newVal, double newValWeight){
return (oldVal * (1.0 - newValWeight)) + (newValWeight * newVal);
}
public static double calcAvg(double oldAvg, int count, double newVal){
return (oldAvg * count + newVal) / (count + 1);
}
public static void writeLogToFile(Context context, boolean onSdcard, String prefix, int timeWindowInSeconds) throws Exception{
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss");
final DateFormat logDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
final long currentTime = System.currentTimeMillis();
final long startTime = currentTime - timeWindowInSeconds * 1000;
final String currentYear = Calendar.getInstance().get(Calendar.YEAR) + "-";
final String logFileName = prefix + sdf.format(new Date(currentTime)) + ".log";
BufferedReader logcatIn;
Process logcat;
OutputStream logFile;
try{
logcat = Runtime.getRuntime().exec("logcat -v time -d *:d");
logcatIn = new BufferedReader(new InputStreamReader(logcat
.getInputStream()), 1024);
}catch(IOException e){
throw new Exception("Unable to launch logcat: " + e.getMessage(), e);
}
try{
if (onSdcard){
logFile = new FileOutputStream(new File(Environment.getExternalStorageDirectory(), logFileName));
}else{
logFile = context.openFileOutput(logFileName, 0);
}
}catch(IOException e){
throw new Exception("Unable to create log file: " + e.getMessage(), e);
}
PrintWriter pw = new PrintWriter(logFile, false);
String line;
long logLineTime;
while ((line = logcatIn.readLine()) != null){
logLineTime = logDF.parse(currentYear + line.substring(0, line.indexOf(".") + 4)).getTime();
if (logLineTime >= startTime){
pw.println(line);
}
}
pw.flush();
pw.close();
logcatIn.close();
logcat.destroy();
}
}
FeatureExtractor.java
import java.util.List;
/**
* A class capable of extracting one or more features. It MUST have a public constructor
* with the following parameters in this order:
* <ul>
* <li>Context context</li>
* <li>Collection<FeatureInfo> featureInfos</li>
* <li>Long timeStamp</li>
* </ul>
*
*/
public interface FeatureExtractor{
/**
* Invoked during a data collection. It is up to the extractor to add the data
* relevant to it's monitored features to the monitoredData list.
*
* #param monitoredData The overall collected data (from all extractors) so far
* #param endTime The time of the current data collection
*/
public void collectData(List<MonitoredData> monitoredData, ParcelableDate endTime);
/**
* Invoked when the feature extractor is no longer needed. This is the place to
* release any resources, unregister any listeners, close any threads, etc.
*/
public void close();
}
FeatureExtractorInitException.java
public class FeatureExtractorInitException extends RuntimeException{
private static final long serialVersionUID = 1L;
public FeatureExtractorInitException(String message){
super(message);
}
public FeatureExtractorInitException(String message, Throwable t){
super(message, t);
}
public FeatureExtractorInitException(Throwable t){
super(t);
}
}

For example if you had an imageView one way of fetching coordinates is...
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
int[] values = new int[2];
view.getLocationOnScreen(values);
Log.d("X & Y",values[0]+" "+values[1]);
}
});
Check out these ST threads:
How to get imageView inside onTouchEvent(MotionEvent event) in android
Android: How do I get the x y coordinates within an image / ImageView?
OnClickListener - x,y location of event?
Find layout with x,y coordinate

If you use reuf codes,you will need to use ParcelableData.java.I add ParcelableData class that found here and hope to save your time:
package dev.drsoran.moloko.service.parcel;
import java.util.Date;
import android.os.Parcel;
import android.os.Parcelable;
public class ParcelableDate implements Parcelable
{
public static final Parcelable.Creator< ParcelableDate > CREATOR = new Parcelable.Creator< ParcelableDate >()
{
public ParcelableDate createFromParcel( Parcel source )
{
return new ParcelableDate( source );
}
public ParcelableDate[] newArray( int size )
{
return new ParcelableDate[ size ];
}
};
private final Date date;
public ParcelableDate( final Date date )
{
this.date = date;
}
public ParcelableDate( long millis )
{
this.date = new Date( millis );
}
public ParcelableDate( Parcel source )
{
date = new Date( source.readLong() );
}
public Date getDate()
{
return date;
}
#Override
public String toString()
{
return date.toString();
}
public int describeContents()
{
return 0;
}
public void writeToParcel( Parcel dest, int flags )
{
dest.writeLong( date.getTime() );
}
}

Related

When using setOnGroupClickListener method report an error “cannot find symbol”

When using setOnGroupClickListener method report an error “cannot find symbol”,
I try to use setOnGroupClickListener to register sublist click event listener to list control,But an error is reported during compilation
error report:
vendor/proprietary/modem/ModemTestBox/src/com/xiaomi/mtb/activity/MtbNvAutoCheckList1Activity.java:142: error: cannot find symbol
elvBook.setOnGroupClickListener(new ExpandableListView.setOnGroupClickListener(){
vendor/proprietary/modem/ModemTestBox/src/com/xiaomi/mtb/activity/MtbNvAutoCheckList1Activity.java:143: error: method does not override or implement a method from a supertype
#Override
package com.mtb.activity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ExpandableListView;
import com.xiaomi.mtb.*;
import com.xiaomi.mtb.activity.*;
import com.xiaomi.mtb.R;
import android.util.Log;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class MtbNvAutoCheckList1Activity extends MtbBaseActivity {
private ArrayList<NvAutoCheckDataFather> groups = new ArrayList<>();
private ArrayList<ArrayList<NvAutoCheckDataSon>>children = new ArrayList<>();
private ArrayList<NvAutoCheckDataSon>data=new ArrayList<>();
private HashMap<Integer,Integer>hashMap=new HashMap<>();
private static int mNvEfsDataPrintMaxNum = 20;
private static final String LOG_TAG = "MtbNvAutoCheckMainActivity";
private static final int DATA_TYPE_DECIMALISM = 0;
private static int mHexOrDec = DATA_TYPE_DECIMALISM;
private static final int DATA_TYPE_HEX = 1;
private static final int SIGNED_DATA = 0;
private static final int UNSIGNED_DATA = 1;
private static boolean mTmpLogPrintFlag = false;
private ExpandableListView elvBook;
private NvAutoCheckBookAdapter adapter;
private static HashMap<Integer,byte[]>mNvData=new HashMap<Integer,byte[]>(){
{
put(550,new byte[]{8,(byte)138, 70, 115, 6, 98, 16, 5, 112});
put(74,new byte[]{6});
put(453,new byte[]{1});
}
};
#SuppressLint("MissingInflatedId")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMtbHookAgent = MtbHookAgent.getHook();
int num=0;
Iterator<Map.Entry<Integer,byte[]>> iterator1=mNvData.entrySet().iterator();
while(iterator1.hasNext()){
Map.Entry<Integer,byte[]>entry=iterator1.next();
int key=entry.getKey();
byte[] value=entry.getValue();
ByteBuffer byteBuf=mMtbHookAgent.onHookNvOptSync(0, key, mMtbHookAgent.EVENT_OEMHOOK_XIAOMI_NV_READ);
log("onNvEfsReadHookHdl, mNvId = "+key);
int ret = byteBuf.getInt();
int len = byteBuf.getInt();
log("onNvEfsReadHookHdl" + ", len = " + len);
byte[] bytes = null;
if(len<=0){
log("efs config empty");
}else{
bytes = new byte[len];
byteBuf.get(bytes);
}
String mNvFlagResult="false";
for(int i=0; i < value.length;i++){
if(entry.getValue()[i] != bytes[i]){
log("mNVDATA_"+key+"[" + i + "] not the same");
break;
}
log("mNVDATA_"+key+"[" + i + "] identical");
if(i == (value.length - 1)){
mNvFlagResult = "success";
}
}
groups.add(new NvAutoCheckDataFather(key,mNvFlagResult));
if(mNvFlagResult=="false"){
hashMap.put(num, hashMap.size());
NvAutoCheckDataSon mNvAutoCheckDataSon=new NvAutoCheckDataSon("正确的值是: "+onGetStringByByteGroup(value,value.length),"读出的值为: "+onGetStringByByteGroup(bytes,value.length));
children.add(new ArrayList<NvAutoCheckDataSon>(){
{
add(mNvAutoCheckDataSon);
}
});
}
num++;
}
// 利用布局资源文件设置用户界面
setContentView(R.layout.nv_auto_check_list1_config);
// 通过资源标识获得控件实例
elvBook = findViewById(R.id.elvBook);
// 创建适配器
adapter = new NvAutoCheckBookAdapter(this, groups, children, hashMap);
// 给列表控件设置适配器
elvBook.setAdapter(adapter);
// 给列表控件注册子列表单击事件监听器
elvBook.setOnGroupClickListener(new ExpandableListView.setOnGroupClickListener(){
#Override
public boolean onGroupClick(ExpandableListView expandableListView, View view, int groupPosition,long l){
if(!hashMap.containsKey(groupPosition)){
return true;
}else{
return false;
}
}
});
}
private static void log(String msg) {
Log.d(LOG_TAG, "MTB_ " + msg);
}
private String onGetStringByDateType(byte val, int uFlag, boolean bPrint) {
return onGetStringByDateType(val, uFlag, bPrint, mHexOrDec, true);
}
private String onGetStringByDateType(byte val, int uFlag, boolean bPrint, int hexOrDec, boolean fillHexZero) {
if (bPrint) {
tmpLog("onGetStringByDateType, byte, val = " + val + ", uFlag = " + uFlag + ", bPrint = " + bPrint + ", hexOrDec = " + hexOrDec + ", fillHexZero = " + fillHexZero);
}
String strVal = null;
BigDecimal bigVal;
byte lowVal = 0;
if (DATA_TYPE_HEX == hexOrDec) {
strVal = Integer.toHexString(val & 0xff);
if (1 == strVal.length() && fillHexZero) {
strVal = "0" + strVal;
}
if (bPrint) {
tmpLog("HEX, strVal = " + strVal);
}
} else {
strVal = "" + val;
if (UNSIGNED_DATA == uFlag && val < 0) {
lowVal = (byte)(val & 0x7f);
bigVal = BigDecimal.valueOf(lowVal).add(BigDecimal.valueOf(Byte.MAX_VALUE)).add(BigDecimal.valueOf(1));
strVal = bigVal.toString();
if (bPrint) {
tmpLog("val < 0, new strVal = " + strVal);
}
}
}
if (null != strVal) {
strVal = strVal.toUpperCase();
}
return strVal;
}
private String onGetStringByByteGroup(byte[] bytes, int len){
String ret="";
for(int i=0;i<len;i++){
String str1=onGetStringByDateType(bytes[i], UNSIGNED_DATA, false);
ret+=str1;
}
return ret;
}
private static void tmpLog(String msg) {
if (mTmpLogPrintFlag) {
log(msg);
}
}
}

sendUserActionEvent () mViwe == null error when using DB

i'm S4 user and my android ver. is 18(4.3.3).
um....while i make an app, i got some problem ( sendUserActionEvent () mViwe == null ), so i want someone's help. PLZ help me:)
here's my code where error has occurred
...
try{
body = m_et_inc_bdy.toString();
mny = Integer.parseInt(m_et_inc_mny.toString());
ord = yr*10000+mth*100+day;
m_dao.Append(body, mny, yr, mth, day, ord);
Toast.makeText(this, "REG success.", Toast.LENGTH_SHORT).show();
finish();
}catch(Exception ig)
{
Toast.makeText(this, "pre_DB_Error", Toast.LENGTH_LONG).show();
ig.printStackTrace();
finish();
}
...
and, m_dao.Append method is this code.
public void Append(String body, int mny, int yr, int mth, int day, int ord ) throws Exception{
str_query="'"+body+"',"+mny+","+yr+","+mth+","+day+","+ord;
_db_.execSQL("insert into HAC (body, money, dateyear, datemonth, dateday, ord) values("+str_query+") ");
}
i think i have no mistake in my code, but it doesn't work..(with logcat's error msg "sendUserActionEvent () mViwe == null")
can someone help me?? please:)
/* and, this is whole code*/
package com.example.accountbook;
import java.util.*;
import android.app.*;
import android.app.DatePickerDialog.OnDateSetListener;
import android.os.*;
import android.view.*;
import android.widget.*;
import com.example.accountbook.db.*;
public class InpIncActivity extends Activity implements View.OnClickListener{
private RankDAO m_dao = null;
private Button m_btn_date = null;
private Button m_btn_input = null;
private Button m_btn_cancel = null;
private EditText m_et_inc_bdy = null;
private EditText m_et_inc_mny = null;
private DatePickerDialog dlg = null;
private OnDateSetListener listener = null;
private int yr = 0;
private int mth = 0;
private int day = 0;
private int mny = 0;
private int ord = 0;
String body;
String date = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_in_inc);
setBindingButtons();
setBindingText();
setBingingDialog();
setBindingRank();
}
private void setBindingButtons()
{
m_btn_date=(Button)findViewById(R.id.btn_ia_date);
m_btn_input=(Button)findViewById(R.id.btn_ia_input);
m_btn_cancel=(Button)findViewById(R.id.btn_ia_cancel);
m_btn_date.setOnClickListener(this);
m_btn_input.setOnClickListener(this);
m_btn_cancel.setOnClickListener(this);
}
private void setBindingText()
{
m_et_inc_bdy=(EditText)findViewById(R.id.et_ia_bd);
m_et_inc_mny=(EditText)findViewById(R.id.et_ia_mny);
}
public void onClick(View v)
{
if(v==m_btn_date)
{
dlg.show();
}
else if(v==m_btn_input)
{
try{
body=m_et_inc_bdy.toString();
mny=Integer.parseInt(m_et_inc_mny.toString());
ord=yr*10000+mth*100+day;
m_dao.Append(body, mny, yr, mth, day, ord);
Toast.makeText(this, "REG success", Toast.LENGTH_SHORT).show();
finish();
}catch(Exception ig)
{
Toast.makeText(this, "pre_DB_Error", Toast.LENGTH_LONG).show();
ig.printStackTrace();
finish();
}
}
else if(v==m_btn_cancel)
{
finish();
}
}
public void setBingingDialog()
{
this.listener = new OnDateSetListener()
{
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
yr=year;
mth=monthOfYear+1;
day=dayOfMonth;
if(mth<10)
date=String.valueOf(yr)+".0"+String.valueOf(mth)+"."+String.valueOf(day);
else
date=String.valueOf(yr)+"."+String.valueOf(mth)+"."+String.valueOf(day);
m_btn_date.setText(date);
}
};
this.dlg=new DatePickerDialog(this, listener,Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get(Calendar.MONTH), Calendar.getInstance().get(Calendar.DATE));
}
public void setBindingRank()
{
try{
m_dao=RankDAO.GetInstance(this);
}catch(Exception e){
Toast.makeText(this, "DB ERROR", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
package com.example.accountbook.db;
import java.util.*;
import com.example.accountbook.*;
import android.app.*;
import android.database.*;
import android.database.sqlite.*;
public class RankDAO {
private static RankDAO _instance_ = null;
private static Activity _activity_ = null;
private SQLiteDatabase _db_ = null;
private int year = 0;
private int month = 0;
private int day = 0;
private int money = 0;
String body = null;
String val = null;
String str_query = null;
private RankDAO() throws Exception{
super();
OpenDatabase();
}
public static synchronized RankDAO GetInstance(Activity act) throws Exception{
if(_instance_ == null) {
_activity_ = act;
_instance_ = new RankDAO();
}
return _instance_;
}
private void OpenDatabase() throws Exception {
try{
if(_db_ == null){
_db_ = _activity_.openOrCreateDatabase("db", Activity.MODE_PRIVATE, null);
//_db_.execSQL("drop table HAC");
_db_.execSQL("Create Table IF NOT EXISTS HAC (body varchar(127), money int(8), dateyear int(4), datemonth int(2), dateday int(2), ord int(8) )");
// _db_AC.execSQL("Create Index IF NOT EXISTS IDX_HAC ON HAC (dateyear asc, datemonth asc, dateday asc)");
}
}catch(Exception ig){
ig.printStackTrace();
throw ig;
}
}
public void Append(String body, int mny, int yr, int mth, int day, int ord ) throws Exception{
str_query="'"+body+"',"+mny+","+yr+","+mth+","+day+","+ord;
_db_.execSQL("insert into HAC (body, money, dateyear, datemonth, dateday, ord) values("+str_query+") ");
}
public ArrayList<HashMap<String,String >> GetRankData(){
ArrayList<HashMap<String,String>> _Items = new ArrayList<HashMap<String,String>>();
Cursor _cursor = _db_.rawQuery("Select * From HAC Order By ord desc ", null);
if(_cursor.moveToFirst()){
do{
body = _cursor.getString(0);
money = Integer.parseInt(_cursor.getString(1));
year = Integer.parseInt(_cursor.getString(2));
month = Integer.parseInt(_cursor.getString(3));
day = Integer.parseInt(_cursor.getString(4));
val =String.valueOf(year)+"."+String.valueOf(month)+"."+String.valueOf(day)+"\t"+String.valueOf(money);
HashMap<String,String> _Item = new HashMap<String,String>();
_Item.put("value",val); // No. 이름
_Item.put("body", body); // 시간
_Items.add(_Item);
MainActivity.mymoney(money);
if(year==Calendar.getInstance().get(Calendar.YEAR) && month==Calendar.getInstance().get(Calendar.MONTH) && day==Calendar.getInstance().get(Calendar.DATE))
MainActivity.todinc(money);
}while(_cursor.moveToNext());
_cursor.close();
}
return _Items;
}
}

How can I fix (The left-hand side of an assignment must be a variable) and (Type mismatch: cannot convert from Object to String) in this code?

I have this code for compressing pictures , I have two error , I have separated these errors with line in code like this (...........) first is : The left-hand side of an assignment must be a variable .......... and the second is Type mismatch: cannot convert from Object to String ................. how can I fix them ???
package com.example.resizingimages;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.media.MediaScannerConnection;
import android.media.MediaScannerConnection.MediaScannerConnectionClient;
import android.media.MediaScannerConnection.OnScanCompletedListener;
import android.net.Uri;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio.Media;
import android.provider.MediaStore.Images.Media;
import android.provider.MediaStore.Video.Media;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsoluteLayout;
import android.widget.AbsoluteLayout.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.InputStream;
import java.io.PrintStream;
public class GetImageActivity extends Activity
implements MediaScannerConnection.MediaScannerConnectionClient, DialogInterface
{
private static final int CAMERA_REQUEST = 1800;
private static final int GALLERY_KITKAT_INTENT_CALLED = 1500;
private static final int SELECT_PICTURE = 1;
static String filePath;
private TextView Name;
private TextView Size;
MediaScannerConnection conn;
File file;
private String filename;
private int height;
Uri imageUri;
private ImageView img;
private Uri outputFileUri;
Uri outputFileUri1;
String path1;
private String path2;
private Bitmap picture;
private File root;
File sdImageMainDirectory;
private Uri selectedImageUri;
private int width;
private void cameraaa(String paramString, Uri paramUri)
{
while (true)
{
try
{
InputStream localInputStream = getContentResolver().openInputStream(paramUri);
BitmapFactory.Options localOptions = new BitmapFactory.Options();
localOptions.inSampleSize = 2;
localOptions.inPurgeable = true;
byte[] arrayOfByte = new byte[1024];
localOptions.inPreferredConfig = Bitmap.Config.RGB_565;
localOptions.inTempStorage = arrayOfByte;
this.picture = BitmapFactory.decodeStream(localInputStream, null, localOptions);
switch (new ExifInterface(paramString).getAttributeInt("Orientation", 1))
{
case 4:
case 5:
default:
this.img.setImageBitmap(this.picture);
String str = sizee(paramUri);
Toast.makeText(getApplicationContext(), "Size of Image " + str, 0).show();
System.out.println("Image Path : " + paramString);
return;
case 6:
rotateImage(this.picture, 90);
continue;
case 3:
}
}
catch (Exception localException)
{
Toast.makeText(getApplicationContext(), "Error " + localException.getMessage(), 0).show();
return;
}
rotateImage(this.picture, 180);
}
}
public static String getDataColumn(Context paramContext, Uri paramUri, String paramString, String[] paramArrayOfString)
{
Cursor localCursor = null;
String[] arrayOfString = { "_data" };
try
{
localCursor = paramContext.getContentResolver().query(paramUri, arrayOfString, paramString, paramArrayOfString, null);
if ((localCursor != null) && (localCursor.moveToFirst()))
{
String str = localCursor.getString(localCursor.getColumnIndexOrThrow("_data"));
return str;
}
}
finally
{
if (localCursor != null)
localCursor.close();
}
if (localCursor != null)
localCursor.close();
return null;
}
public static String getPathl(Context paramContext, Uri paramUri)
{
int i;
if (Build.VERSION.SDK_INT >= 19)
i = 1;
while ((i != 0) && (DocumentsContract.isDocumentUri(paramContext, paramUri)))
if (isExternalStorageDocument(paramUri))
{
String[] arrayOfString3 = DocumentsContract.getDocumentId(paramUri).split(":");
if (!"primary".equalsIgnoreCase(arrayOfString3[0]))
break label271;
return Environment.getExternalStorageDirectory() + "/" + arrayOfString3[1];
i = 0;
}
else
{
if (isDownloadsDocument(paramUri))
{
String str2 = DocumentsContract.getDocumentId(paramUri);
return getDataColumn(paramContext, ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(str2).longValue()), null, null);
}
if (!isMediaDocument(paramUri))
break label271;
String[] arrayOfString1 = DocumentsContract.getDocumentId(paramUri).split(":");
String str1 = arrayOfString1[0];
Uri localUri;
if ("image".equals(str1))
localUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
while (true)
{
String[] arrayOfString2 = new String[1];
arrayOfString2[0] = arrayOfString1[1];
return getDataColumn(paramContext, localUri, "_id=?", arrayOfString2);
if ("video".equals(str1))
{
localUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
}
else
{
boolean bool = "audio".equals(str1);
localUri = null;
if (bool)
localUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
}
}
if ("content".equalsIgnoreCase(paramUri.getScheme()))
return getDataColumn(paramContext, paramUri, null, null);
if ("file".equalsIgnoreCase(paramUri.getScheme()))
return paramUri.getPath();
label271: return filePath;
}
public static boolean isDownloadsDocument(Uri paramUri)
{
return "com.android.providers.downloads.documents".equals(paramUri.getAuthority());
}
public static boolean isExternalStorageDocument(Uri paramUri)
{
return "com.android.externalstorage.documents".equals(paramUri.getAuthority());
}
public static boolean isMediaDocument(Uri paramUri)
{
return "com.android.providers.media.documents".equals(paramUri.getAuthority());
}
private void openAddPhoto()
{
String[] arrayOfString = { "Camera", "Gallery" };
AlertDialog.Builder localBuilder = new AlertDialog.Builder(this);
localBuilder.setTitle(getResources().getString(2130968578));
localBuilder.setItems(arrayOfString, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)
{
if (paramAnonymousInt == 0)
{
ContentValues localContentValues = new ContentValues();
localContentValues.put("title", "new-photo-name.jpg");
localContentValues.put("description", "Image capture by camera");
GetImageActivity.this.imageUri = GetImageActivity.this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, localContentValues);
Intent localIntent1 = new Intent("android.media.action.IMAGE_CAPTURE");
localIntent1.putExtra("output", GetImageActivity.this.imageUri);
GetImageActivity.this.startActivityForResult(localIntent1, 1800);
}
if (paramAnonymousInt == 1)
{
if (Build.VERSION.SDK_INT < 19)
{
Intent localIntent2 = new Intent();
localIntent2.setType("image/*");
localIntent2.setAction("android.intent.action.GET_CONTENT");
GetImageActivity.this.startActivityForResult(Intent.createChooser(localIntent2, "Select Picture"), 1);
}
}
else
return;
Intent localIntent3 = new Intent("android.intent.action.PICK", MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
GetImageActivity.this.startActivityForResult(Intent.createChooser(localIntent3, "Select Picture"), 1500);
}
});
localBuilder.setNeutralButton("cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)
{
paramAnonymousDialogInterface.dismiss();
}
});
localBuilder.show();
}
private void startScan()
{
if (this.conn != null)
this.conn.disconnect();
this.conn = new MediaScannerConnection(this, this);
this.conn.connect();
}
public void cancel()
{
}
public void dismiss()
{
}
public String getPath(Uri paramUri)
{
Cursor localCursor = managedQuery(paramUri, new String[] { "_data" }, null, null, null);
String str = null;
if (localCursor != null)
{
int i = localCursor.getColumnIndexOrThrow("_data");
localCursor.moveToFirst();
str = localCursor.getString(i);
}
return str;
}
public String name(String paramString)
{
int i = 0;
for (int j = 0; ; j++)
{
if (j >= paramString.length())
{
this.filename = filePath.substring(i + 1, paramString.length());
return this.filename;
}
if (paramString.charAt(j) == '/')
i = j;
}
}
public void onActivityResult(int paramInt1, int paramInt2, Intent paramIntent)
{
if (paramInt2 == -1)
{
if (paramInt1 == 1)
while (true)
{
try
{
this.selectedImageUri = paramIntent.getData();
Toast.makeText(getApplicationContext(), "DATA " + filePath, 0).show();
filePath = getPath(this.selectedImageUri);
InputStream localInputStream2 = getContentResolver().openInputStream(this.selectedImageUri);
BitmapFactory.Options localOptions2 = new BitmapFactory.Options();
localOptions2.inSampleSize = 2;
localOptions2.inPurgeable = true;
byte[] arrayOfByte2 = new byte[1024];
localOptions2.inPreferredConfig = Bitmap.Config.RGB_565;
localOptions2.inTempStorage = arrayOfByte2;
this.picture = BitmapFactory.decodeStream(localInputStream2, null, localOptions2);
switch (new ExifInterface(filePath).getAttributeInt("Orientation", 1))
{
case 4:
case 5:
default:
this.img.setImageBitmap(this.picture);
String str4 = sizee(this.selectedImageUri);
Toast.makeText(getApplicationContext(), "Size of Image " + str4, 0).show();
return;
case 6:
rotateImage(this.picture, 90);
continue;
case 3:
}
}
catch (Exception localException3)
{
Toast.makeText(getApplicationContext(), "Error " + localException3.getMessage(), 0).show();
return;
}
rotateImage(this.picture, 180);
}
if (paramInt1 == 1500)
while (true)
{
try
{
this.selectedImageUri = paramIntent.getData();
getPathl(getApplicationContext(), this.selectedImageUri);
getContentResolver();
filePath = getPathl(getApplicationContext(), this.selectedImageUri);
InputStream localInputStream1 = getContentResolver().openInputStream(this.selectedImageUri);
BitmapFactory.Options localOptions1 = new BitmapFactory.Options();
localOptions1.inSampleSize = 2;
localOptions1.inPurgeable = true;
byte[] arrayOfByte1 = new byte[1024];
localOptions1.inPreferredConfig = Bitmap.Config.RGB_565;
localOptions1.inTempStorage = arrayOfByte1;
this.picture = BitmapFactory.decodeStream(localInputStream1, null, localOptions1);
switch (new ExifInterface(filePath).getAttributeInt("Orientation", 1))
{
case 4:
case 5:
default:
this.img.setImageBitmap(this.picture);
String str3 = sizee(this.selectedImageUri);
Toast.makeText(getApplicationContext(), "Size of Image " + str3, 0).show();
return;
case 6:
case 3:
}
}
catch (Exception localException2)
{
Toast.makeText(getApplicationContext(), "Error " + localException2.getMessage(), 0).show();
return;
}
rotateImage(this.picture, 90);
continue;
rotateImage(this.picture, 180);
}
if (paramInt1 == 1800)
{
filePath = null;
this.selectedImageUri = this.imageUri;
if (this.selectedImageUri != null)
while (true)
{
String str1;
try
{
str1 = this.selectedImageUri.getPath();
String str2 = getPath(this.selectedImageUri);
if (str2 != null)
{
filePath = str2;
if (filePath == null)
break;
Toast.makeText(getApplicationContext(), " path" + filePath, 1).show();
new Intent(getApplicationContext(), GetImageActivity.class);
cameraaa(filePath, this.selectedImageUri);
return;
}
}
catch (Exception localException1)
{
Toast.makeText(getApplicationContext(), "Internal error", 1).show();
Log.e(localException1.getClass().getName(), localException1.getMessage(), localException1);
return;
}
if (str1 != null)
{
filePath = str1;
}
else
{
Toast.makeText(getApplicationContext(), "Unknown path", 1).show();
Log.e("Bitmap", "Unknown path");
}
}
}
}
}
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
requestWindowFeature(1);
getWindow().setFlags(1024, 1024);
setContentView(2130903040);
Display localDisplay = getWindowManager().getDefaultDisplay();
this.width = localDisplay.getWidth();
this.height = localDisplay.getHeight();
final Button localButton = (Button)findViewById(2131296257);
final Spinner localSpinner = (Spinner)findViewById(2131296260);
final TextView localTextView = (TextView)findViewById(2131296259);
localButton.setVisibility(4);
localSpinner.setVisibility(4);
localTextView.setVisibility(4);
if (this.height <= 480)
{
localSpinner.setLayoutParams(new AbsoluteLayout.LayoutParams(-1, -2, 0, 20 + (this.height - this.height / 3)));
localTextView.setLayoutParams(new AbsoluteLayout.LayoutParams(this.width, 60, 0, -20 + (this.height - this.height / 3)));
localTextView.setText("Image Quality");
localTextView.setText("Image Quality");
this.img = ((ImageView)findViewById(2131296258));
this.img.setBackgroundResource(2130837504);
//first error is here
.......................................................................................
***(-160 + this.height);***
(-160 + this.height);
((int)(0.8D * this.width));
AbsoluteLayout.LayoutParams localLayoutParams1 = new AbsoluteLayout.LayoutParams((int)(0.8D * this.width), (int)(0.5D * this.height), (int)(this.width - 0.9D * this.width), (int)(this.height - 0.9D * this.height));
this.img.setLayoutParams(localLayoutParams1);
ImageView localImageView = this.img;
View.OnClickListener local1 = new View.OnClickListener()
{
public void onClick(View paramAnonymousView)
{
GetImageActivity.this.img.setImageDrawable(null);
GetImageActivity.this.img.setBackgroundResource(2130837504);
localButton.setVisibility(0);
localSpinner.setVisibility(0);
localTextView.setVisibility(0);
GetImageActivity.this.openAddPhoto();
}
};
localImageView.setOnClickListener(local1);
if (this.height > 480)
break label505;
localButton.setBackgroundResource(2130837507);
(-160 + this.height);
}
for (AbsoluteLayout.LayoutParams localLayoutParams2 = new AbsoluteLayout.LayoutParams(50, 50, -25 + this.width / 2, -51 + this.height); ; localLayoutParams2 = new AbsoluteLayout.LayoutParams(170, 170, -85 + this.width / 2, -170 + this.height))
{
localButton.setLayoutParams(localLayoutParams2);
View.OnClickListener local2 = new View.OnClickListener()
{
public void onClick(View paramAnonymousView)
{
}
};
localButton.setOnClickListener(local2);
return;
localSpinner.setLayoutParams(new AbsoluteLayout.LayoutParams(-1, -2, 0, 30 + (this.height - this.height / 3)));
localTextView.setLayoutParams(new AbsoluteLayout.LayoutParams(this.width, 60, 0, -10 + (this.height - this.height / 3)));
break;
label505: localButton.setBackgroundResource(2130837506);
(-160 + this.height);
}
}
public boolean onCreateOptionsMenu(Menu paramMenu)
{
getMenuInflater().inflate(2131230720, paramMenu);
return true;
}
public void onMediaScannerConnected()
{
try
{
this.conn.scanFile(filePath, "image/*");
return;
}
catch (IllegalStateException localIllegalStateException)
{
}
}
public boolean onOptionsItemSelected(MenuItem paramMenuItem)
{
if (paramMenuItem.getItemId() == 2131296262)
shareagain();
while (true)
{
return true;
if (paramMenuItem.getItemId() == 2131296263)
try
{
startActivity(new Intent(this, readddme.class));
}
catch (Exception localException)
{
Toast.makeText(getApplicationContext(), "Error " + localException.getMessage(), 0).show();
}
else if (paramMenuItem.getItemId() == 2131296264)
System.exit(0);
}
}
public void onScanCompleted(String paramString, Uri paramUri)
{
this.conn.disconnect();
}
public void rotateImage(Bitmap paramBitmap, int paramInt)
{
Matrix localMatrix = new Matrix();
localMatrix.setRotate(paramInt);
this.picture = Bitmap.createBitmap(paramBitmap, 0, 0, paramBitmap.getWidth(), paramBitmap.getHeight(), localMatrix, true);
}
public void share()
{
Intent localIntent = new Intent("android.intent.action.SEND");
localIntent.setType("text/plain");
localIntent.putExtra("android.intent.extra.SUBJECT", "#RABIDO");
localIntent.putExtra("android.intent.extra.TEXT", "#RABIDO");
localIntent.setType("image/*");
localIntent.putExtra("android.intent.extra.STREAM", this.selectedImageUri);
startActivity(Intent.createChooser(localIntent, "Share Image"));
}
public void shareagain()
{
Intent localIntent = new Intent("android.intent.action.SEND");
localIntent.setType("text/plain");
localIntent.putExtra("android.intent.extra.TEXT", "Check out 'RABIDO' - https://play.google.com/store/apps/details?id=decrease.image.uploader");
startActivity(Intent.createChooser(localIntent, "Share via"));
}
public String sizee(Uri paramUri)
{
Object localObject;
try
{
InputStream localInputStream = getContentResolver().openInputStream(paramUri);
byte[] arrayOfByte = new byte[1024];
int i = 0;
float f;
while (true)
{
if (localInputStream.read(arrayOfByte) == -1)
{
f = i / 1000;
if (f >= 1000.0F)
break;
localObject = " " + i / 1000 + " KB";
break label164;
}
i += arrayOfByte.length;
}
String str = " " + f / 1000.0F + " MB";
localObject = str;
}
catch (Exception localException)
{
Toast.makeText(getApplicationContext(), "Error 5 " + localException.getMessage(), 0).show();
return "";
}
//second is here
..................................................................
label164: return localObject;
}
}
For the First error can you try something like this:
(this.height = this.height - 160);
The error indicates you are trying to make an assignment operation but you have not put a variable in the left hand side of the equation.
there may also be a short hand way to do this such as:
(this.height =- 160);
for the second error is seems that you have declared "localObject" as an Object.
can you just declare it as a String. seems that you are assigning a string to it and then wanting to return a string. See if that works.

get return Value null in method in android

I write one function for get data from database.
I have set a breakpoint and make sure the function is already get data for return
but when I use the function I Can't get data back in My main function
is my data structure error? or other thing error?
thanks for your help.
import java.util.ArrayList;
public class ScheduleData {
public String strID;
public String strName;
public String strDesc;
public Integer iScheduleDay;
public String strStartDate;
public ArrayList<ScheduleContent> alPOI;
public ScheduleData() {
strID = new String();
strName = new String();
strDesc = new String();
strStartDate = new String();
iScheduleDay = 0;
alPOI = new ArrayList<ScheduleContent>();
}
}
//
public class ScheduleContent {
public String strPOIID;
public int iSequence ;
public int iDay ;
public String strTime;
public int iStayTime ;
public ScheduleContent() {
iSequence = 1;
iDay = 1;
iStayTime = 0;
}
}
//
public boolean bInitData() {
ArrayList<ScheduleData> alEx = alGetAllSchedule();
}
private ArrayList<ScheduleData> alGetAllSchedule() {
ArrayList<ScheduleData> alTmp = new ArrayList<ScheduleData>();
try {
mDATA.m_alAllSchedule.clear();
Cursor c = objSchedule.getAllCursor();
ScheduleDataInit();
if (c.getCount() > 0) {
if (c.moveToFirst()) {
while (c.isAfterLast() == false) {
ScheduleData sTmp = new ScheduleData();
sTmp.strID = c.getString(c.getColumnIndex("SID"));
sTmp.strName = c.getString(c.getColumnIndex("S_Name"));
sTmp.strDesc = c.getString(c.getColumnIndex("S_Desc"));
sTmp.strStartDate = c.getString(c
.getColumnIndex("S_StartDate"));
sTmp.iScheduleDay = Integer.valueOf(c.getInt(c
.getColumnIndex("S_Day")));
sTmp.alPOI=mDATA.m_hAllScheduleContent.get(sTmp.strID);
alTmp.add(sTmp);
c.moveToNext();
}
}
}
mDATA.m_alAllSchedule = alTmp;
c.close();
} catch (Exception errMsg) {
errMsg.printStackTrace();
}
return alTmp;
}

FTP file upload issue

I need to upload a file from the sdcard to a server(using FTP), but I've encountered some problems when trying to save the file. The file seems to exist at first, but when I choose to play it... well, it just won't (like it crashes during upload rendering it invalid). Any ideas regarding what might going wrong? I've set the extension .mp3, and here's the code:
holder.upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String str_useid = Recording.str_getValue;
if (upload_or_not == true) {
FTPClient con = new FTPClient();
try {
con.connect("FTP URL");
if (con.login("USERNAME", "PASSWORD")) {
Handler progressHandler = new Handler();
con.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
BufferedInputStream buffIn = new BufferedInputStream(
new FileInputStream(
"/sdcard/audiometer/shanesh" +
RequestId[position] + "-"
str_useid + ".mp3"
)
);
con.enterLocalPassiveMode(); // important!
ProgressInputStream progressInput = new ProgressInputStream(
buffIn,
progressHandler
);
boolean status = con.storeFile(
"/Rangam/shanesh" +
RequestId[position] + "-" +
str_useid +
".mp3",
progressInput
);
String filename = "/shanesh" + RequestId[position] +
"-" + str_useid + ".mp3";
buffIn.close();
con.logout();
con.disconnect();
String MachineName = "DOT-NET-SERVER";
sendFlagToServer(RequestId[position], filename, MachineName);
Toast.makeText(
context,
" :: sucessfully upload :: " + status,
Toast.LENGTH_LONG
).show();
Toast.makeText(
context,
" :: RequestId is :: " +
RequestId[position],
Toast.LENGTH_LONG
).show();
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(
context,
" :: File not Found :: ",
Toast.LENGTH_LONG
).show();
}
}
ProgressInputStream.java
package com.RecordingApp;
import java.io.IOException;
import java.io.InputStream;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
public class ProgressInputStream extends InputStream {
/* Key to retrieve progress value from message bundle passed to handler */
public static final String PROGRESS_UPDATE = "progress_update";
private static final int TEN_KILOBYTES = 1024 * 10;
private InputStream inputStream;
private Handler handler;
private long progress;
private long lastUpdate;
private boolean closed;
public ProgressInputStream(InputStream inputStream, Handler handler) {
this.inputStream = inputStream;
this.handler = handler;
this.progress = 0;
this.lastUpdate = 0;
this.closed = false;
}
#Override
public int read() throws IOException {
int count = inputStream.read();
return incrementCounterAndUpdateDisplay(count);
}
#Override
public int read(byte[] b, int off, int len) throws IOException {
int count = inputStream.read(b, off, len);
return incrementCounterAndUpdateDisplay(count);
}
#Override
public void close() throws IOException {
super.close();
if (closed)
throw new IOException("already closed");
closed = true;
}
private int incrementCounterAndUpdateDisplay(int count) {
if (count > 0)
progress += count;
lastUpdate = maybeUpdateDisplay(progress, lastUpdate);
return count;
}
private long maybeUpdateDisplay(long progress, long lastUpdate) {
if (progress - lastUpdate > TEN_KILOBYTES) {
lastUpdate = progress;
sendLong(PROGRESS_UPDATE, progress);
}
return lastUpdate;
}
public void sendLong(String key, long value) {
Bundle data = new Bundle();
data.putLong(key, value);
Message message = Message.obtain();
message.setData(data);
handler.sendMessage(message);
}
}

Categories

Resources