My code works fine when i add the zoom code it gives null pointer exception.
I have written the below code inside the preview class. I am new in android please help thanks in advance.
my code is
int currentZoomLevel = 0, maxZoomLevel = 0;
public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
int width, int height) {
// start preview with new settings
try {
parameters = mCamera.getParameters();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Display display = ((WindowManager) context
.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
if (display.getRotation() == Surface.ROTATION_0) {
try {
parameters.setPreviewSize(height, width);
mCamera.setDisplayOrientation(90);
} catch (Exception e) {
e.printStackTrace();
}
}
if (display.getRotation() == Surface.ROTATION_90) {
try {
parameters.setPreviewSize(width, height);
} catch (Exception e) {
e.printStackTrace();
}
}
if (display.getRotation() == Surface.ROTATION_180) {
try {
parameters.setPreviewSize(height, width);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (display.getRotation() == Surface.ROTATION_270) {
try {
parameters.setPreviewSize(width, height);
mCamera.setDisplayOrientation(180);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This is whera i start zooming. i have add zoom control in side my layout
ZoomControls zoomControls = (ZoomControls) findViewById(R.id.zoom);
if (parameters.isZoomSupported()) {
final int maxZoomLevel = parameters.getMaxZoom();
Log.i("max ZOOM ", "is " + maxZoomLevel);
zoomControls.setIsZoomInEnabled(true);
zoomControls.setIsZoomOutEnabled(true);
zoomControls.setOnZoomInClickListener(new OnClickListener() {
public void onClick(View v) {
if (currentZoomLevel < maxZoomLevel) {
currentZoomLevel++;
mCamera.startSmoothZoom(currentZoomLevel);
parameters.setZoom(currentZoomLevel);
mCamera.setParameters(parameters);
}
}
});
zoomControls.setOnZoomOutClickListener(new OnClickListener() {
public void onClick(View v) {
if (currentZoomLevel > 0) {
currentZoomLevel--;
parameters.setZoom(currentZoomLevel);
mCamera.setParameters(parameters);
}
}
});
} else
zoomControls.setVisibility(View.GONE);
try {
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (Exception e) {
// intentionally left blank for a test
}
}
Related
From https://github.com/ReactiveX/RxJava/wiki/Backpressure-(2.0)
the following snippet is provide to indicate correct usage for RXified file reading.
Flowable<Integer> o = Flowable.generate(
() -> new FileInputStream("data.bin"),
(inputstream, output) -> {
try {
int byte = inputstream.read();
if (byte < 0) {
output.onComplete();
} else {
output.onNext(byte);
}
} catch (IOException ex) {
output.onError(ex);
}
return inputstream;
},
inputstream -> {
try {
inputstream.close();
} catch (IOException ex) {
RxJavaHooks.onError(ex);
}
}
);
I am doing the following
public Flowable<byte[]> createFlowable(File file) {
return Flowable.create(source -> {
try (FileInputStream fin = new FileInputStream(file);
BufferedInputStream in = new BufferedInputStream(fin)) {
while (in.available() > 0) {
byte[] data = getMessageRawData(in);
source.onNext(data);
}
source.onComplete();
}
catch (Exception ex) {
source.onError(ex);
}
}, BackpressureStrategy.BUFFER);
}
Does my code (uses try with resource) suffer from resource leakage if dispose is called mid way or what other side effects can be expected or is it just a different way of doing things?
This is my code :
There is two condition is happening :
1.Not getting chat continued when i received pending message form other side:
2.When internet goes when i disconnecting the XMPP connection then pending message has not coming but chat will continued
public void init(String userId, String pwd) {
Log.i("XMPP", "Initializing!");
mPassword = DatabaseManager.Session.getClientPassword(this);
HOST = "xm3.conversity.net";
xMppUserName = DatabaseManager.Session.getXmppUserName(this);
xMppOnlyUserName = xMppUserName.split("#")[0];
agentId = DatabaseManager.Session.getAgentNameId(this);
PORT = DatabaseManager.Session.getPortNumber(this);
Log.e("xmpp", "mPassword:" + mPassword);
Log.e("xmpp", "HOST:" + HOST);
Log.e("xmpp", "xMppOnlyUserName:" + xMppOnlyUserName);
Log.e("xmpp", "xMppUserName:" + xMppUserName);
Log.e("xmpp", "agentId:" + agentId);
Log.e("xmpp", "PORT:" + String.valueOf(PORT));
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setUsernameAndPassword(xMppUserName, passWord);
configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
configBuilder.setResource("Android");
configBuilder.setServiceName(DOMAIN);
configBuilder.setHost(HOST);
configBuilder.setPort(PORT);
configBuilder.setSendPresence(true);
configBuilder.setDebuggerEnabled(true);
configBuilder.setCompressionEnabled(true);
connection = new XMPPTCPConnection(configBuilder.build());
connection.addConnectionListener(connectionListener);
// ReconnectionManager.getInstanceFor(connection).enableAutomaticReconnection();
// connection.setPacketReplyTimeout(10000);
// PingManager.setDefaultPingInterval(600);
// PingManager.getInstanceFor(connection).registerPingFailedListener((PingFailedListener) this);
chatmanager = ChatManager.getInstanceFor(connection);
chatmanager.addChatListener(new ChatManagerListener() {
#Override
public void chatCreated(Chat chat, boolean createdLocally) {
chat.addMessageListener(new ChatMessageListener() {
#Override
public void processMessage(Chat chat, final Message message) {
Log.e("Xmpp", String.valueOf(chat) + " === " + message.toString() + "MESSAGE: " + message.getBody());
Handler refresh = new Handler(Looper.getMainLooper());
refresh.post(new Runnable() {
public void run() {
Log.e("Xmpp", "RECIVE MESSAGE: " + message.getBody() + message.getFrom() + "StanzaID: " + message.getBodies());
String[] strings = {message.getBody(), "2", Utility.getCurrentTime(), message.getThread(), "A", "6", "7", DatabaseManager.Message.START_CHAT, ""};
DatabaseManager.Message.insertValues(getApplicationContext(), strings);
Intent i = new Intent(ChatActivity.CHAT_BROADCAST);
i.putExtra(ChatActivity.KEY_ACTION, ChatActivity.NEW_MESSAGE);
getApplicationContext().sendBroadcast(i);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Do something after 5s = 5000ms
// disconnectConnection();
}
}, 3000);
}
});
}
});
}
});
}
// Disconnect Function
public void disconnectConnection() {
new Thread(new Runnable() {
#Override
public void run() {
connection.disconnect();
Log.e("xmpp", "connection.disconnect();");
}
}).start();
}
public void connectConnection() {
AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {
#Override
protected Boolean doInBackground(Void... arg0) {
// Create a connection
try {
connection.connect();
login();
connected = true;
final ScheduledExecutorService scheduleTaskExecutor = Executors.newSingleThreadScheduledExecutor();
scheduleTaskExecutor.scheduleWithFixedDelay(new Runnable() {
#Override
public void run() {
Log.d("xmpp", "inside run()");
Log.d("xmpp", "isconnect: " + connection.isConnected() + " Auth: " + connection.isAuthenticated());
/* if(!Utility.isNetworkAvailable(getApplicationContext())){
// disconnectConnection();
}
else */
if (connection.isConnected()) {
sendMessagesToServer();
} else {
try {
connection.connect();
login();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
}
}
}, 0, 2, TimeUnit.SECONDS);
} catch (IOException e) {
} catch (SmackException e) {
} catch (XMPPException e) {
}
return null;
}
};
connectionThread.execute();
}
private void sendMessagesToServer() {
try {
connection.sendPacket(new Presence(Presence.Type.available));
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
// Log.e(TAG,"in side sendMessagesToServer()");
DatabaseManager dbManager = new DatabaseManager(this);
dbManager.open();
Cursor c = dbManager.getMessages();
while (c.moveToNext()) {
//Read the message details
String status = c.getString(DatabaseManager.Message.INDEX_STATUS);
// Log.e("PREM", status + String.valueOf(status.equalsIgnoreCase("P")));
if (status.equalsIgnoreCase("P")) {
String message = c.getString(DatabaseManager.Message.INDEX_MESSAGE);
String id = c.getString(0);
sendMsg(message);
dbManager.updateMessageStatus(id, jid);
}
}
c.close();
dbManager.close();
}
public void sendMsg(String message) {
if (connection.isConnected() == true) {
// Assume we've created an XMPPConnection name "connection"._
chatmanager = ChatManager.getInstanceFor(connection);
newChat = chatmanager.createChat(agentId);
try {
newChat.sendMessage(message);
jid = newChat.getThreadID();
Log.i("Xmpp", "message send to server");
Log.i("Xmpp", "thread: " + newChat.getThreadID() + " Listner: " + newChat.getListeners() + " participant" + newChat.getParticipant());
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
}
public void login() {
try {
connection.login(xMppOnlyUserName, DatabaseManager.Session.getClientPassword(this));
Log.i("Xmpp", "Yey! We're connected to the Xmpp server!");
} catch (XMPPException | SmackException | IOException e) {
e.printStackTrace();
} catch (Exception e) {
}
}
your question is not clear, but from what I understood, you have to save the messages in sqlite database on android, and then load from database everytime you open the chat page
I get "Invalid thread access" in below code. I am not sure where I have written wrong code. My main intention to write the code is to just display subtask (what is happening behind the scene) so I have added subtask before method called.
#Override
public void handleEvent(Event event)
{
if((event.keyCode == SWT.CR || event.keyCode == 13 || event.type == SWT.Selection) && btnAdd.isEnabled())
{
final PreferencesMO permo = new PreferencesMO();
permo.updatePreferences();
permo.updateDocumentNumber();
final ProjectMO pmo = new ProjectMO();
final CoverSheetMO csmo = new CoverSheetMO();
final CommonError cmerror = new CommonError();
final ParameterConfigurationMO pamo = new ParameterConfigurationMO();
final SnippetNew s = new SnippetNew();
final String projName = txtpname.getText();
Display.getDefault().asyncExec(new Runnable()
{
public void run()
{
try
{
new ProgressMonitorDialog(shell).run(true, true, new IRunnableWithProgress() {
#Override
public void run(final IProgressMonitor monitor) throws InvocationTargetException,
InterruptedException
{
monitor.beginTask("Import Data", IProgressMonitor.UNKNOWN);
monitor.subTask("Connecting to databse...");
for(int i=0;i<=100;i++)
{
s.method1(i);
}
//monitor.worked(1);
try { Thread.sleep(2000); } catch (Exception e) { }
monitor.subTask("Analysing Data...");
try { Thread.sleep(2000); } catch (Exception e) { }
if(!projName.equals(""))
{
monitor.subTask("Updating coversheet ...");
try { Thread.sleep(2000); } catch (Exception e) { }
cmerror.updateCoverSheetStatusforNewProject();
monitor.subTask("Inserting Project ...");
try { Thread.sleep(2000); } catch (Exception e) { }
pmo.addProjectManager(projName,"T");
monitor.subTask("Searching Project ID ...");
try { Thread.sleep(2000); } catch (Exception e) { }
String p_id = pmo.searchprojectID(projName);
permo.insertDocumentNumber(p_id);
monitor.subTask("Inserting data into coversheet ...");
try { Thread.sleep(2000); } catch (Exception e) { }
csmo.insertCoversheet(p_id);
pamo.insertParameterConfiguration(p_id);
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().setText("Demo Tool - "+projName);
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
AuditLogs view = (AuditLogs) page.findView(AuditLogs.ID);
IEditorPart editorPart = page.getActiveEditor();
StackedLambdaChartInput input = new StackedLambdaChartInput();
AnalysisResult_MetricsChartInput metricsinput = new AnalysisResult_MetricsChartInput();
StackedLambdaChart_HorizantalInput stackedhorizantalinput = new StackedLambdaChart_HorizantalInput();
AnalysisResult_Metrics_HorizantalChartInput metricshorizantalinput = new AnalysisResult_Metrics_HorizantalChartInput();
BarChartInput inpuit = new BarChartInput();
BarChart_HorizantalInput barchart_horizantalinput = new BarChart_HorizantalInput();
AuditLogMO auditlog = new AuditLogMO();
monitor.subTask("Fetching audit logs to display ...");
try { Thread.sleep(2000); } catch (Exception e) { }
java.util.List<java.util.List<String>> auditlogs = auditlog.searchAuditLog(null,null);
view.table(auditlogs);
try
{
handlerService.executeCommand(AuditLogView.ID, new Event());
handlerService.executeCommand(ErrorLogView.ID, new Event());
handlerService.executeCommand(DesignHierarchyHandler.ID, new Event());
if(myeditor != null)
{
if(myeditor instanceof CoverSheet)
{
handlerService.executeCommand(CoverSheetHandler.ID, new Event());
}
else if(myeditor instanceof ParameterConfigurations)
{
handlerService.executeCommand(ParameterConfigurationHandler.ID, new Event());
}
}
}
catch (ExecutionException | NotDefinedException | NotEnabledException | PartInitException| NotHandledException e1)
{
e1.printStackTrace();
}
Constant con = new Constant();
con.createNewProject();
}
//shell.close();
monitor.done();
}
});
}
catch (InvocationTargetException | InterruptedException e)
{
e.printStackTrace();
}
}
});
}
}
Put your progress monitor as below :
Display.getDefault().asyncExec( new Runnable()
{
IWorkbenchWindow win = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
new ProgressMonitorDialog(shell).run(true, true, new IRunnableWithProgress() {
#Override
public void run(final IProgressMonitor monitor) throws InvocationTargetException,
InterruptedException
{
monitor.beginTask("Import Data", IProgressMonitor.UNKNOWN);
monitor.subTask("Connecting to databse...");
for(int i=0;i<=100;i++)
}
If you want the workbench page, that also has to be called inside a UI thread like above.
You can't access UI code in the background thread used for the IRunnableWithProgress code.
So you must get the values of controls in the UI thread before you run the progress dialog.
You also can't access things like IWorkbenchPage in the background thread. If you want to update UI objects from a non-UI thread, you need to use Display.asyncExec or Display.syncExec to run the updating code in the UI thread.
I would like to know if there is a way to show only a reign of area of the camera that shown on a SurfaceView.
I've got an image like that (microscopic image)
and I want to show image like that(Cropped and Stretched):
This is a part of my code(it is a basic code that show the camera on SurfaceView using SurfaceHolder):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_sample_testing);
overridePendingTransition(0, 0);
cameraView = (SurfaceView)findViewById(R.id.CameraView);
holder = cameraView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
camera = Camera.open();
parameters = camera.getParameters();
parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
parameters.setFocusMode(Parameters.FOCUS_MODE_AUTO);
//parameters.setZoom(10);
camera.setParameters(parameters);
camera.setPreviewDisplay(holder);
camera.setDisplayOrientation(90);
camera.startPreview();
camera.autoFocus(autoFocusCallback);
recorder = new MediaRecorder();
final Timer myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
StartTest(0);
myTimer.cancel();
myTimer.purge();
}
},10000, 10);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void initRecorder() {
camera.unlock();
recorder.setCamera(camera);
recorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
recorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
CamcorderProfile cpHigh = CamcorderProfile
.get(CamcorderProfile.QUALITY_HIGH);
recorder.setProfile(cpHigh);
recorder.setMaxDuration(50000); // 50 seconds
recorder.setMaxFileSize(300000000); // Approximately 5 megabytes
recorder.setOutputFile(VIDEO_PATH);
}
private void prepareRecorder() {
recorder.setPreviewDisplay(holder.getSurface());
try {
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
finish();
} catch (IOException e) {
e.printStackTrace();
finish();
}
}
Thanks for any help!
I have four views in Eclipse RCP App. In that 3 View are responsible to show the multiline graphs. i am using a switch case for drawing the graph continuously until other views are get focused. But the view are not showing the updated chart.
The following is the case for update the graph. i have two datasets for sample updation of the view.
All the replies are appreciated.
case 1:
System.out.println("in Case "+selectedViewId);
while(selectedViewId==1){
try {
Display.getDefault().syncExec(new Runnable() {
public void run() {
while(count<20) {
count++;
System.err.println("Countttttttt "+count);
if(count%2==0){
System.err.println(".....Oneeeeeeee");
IViewPart vp = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findView("RCP.CPU");
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().hideView(vp);
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().resetPerspective();
try {
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView("RCP.CPU");
} catch (PartInitException e1) {
e1.printStackTrace();
}
int value = CPU.value=1;
CPU cpuView = CPUSingleton.getCPUObject();
}
else {
System.err.println(".....tWOOOOOOOOOOOOOO");
IViewPart vp = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findView("RCP.CPU");
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().hideView(vp);
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().resetPerspective();
try {
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView("RCP.CPU");
} catch (PartInitException e) {
e.printStackTrace();
}
int value = CPU.value=2;
CPU cpuView = CPUSingleton.getCPUObject();
}
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
break;