i am developing a android application which uses nanohttpd to create a webserver my code do not give me any error but the server is not running because when i go to xx.xxx.xxx.xxx:8765/index.htm then it gives my no result this is my code:
Please Help...
package dolphin.developers.com;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import dolphin.devlopers.com.R;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
public class AlertDialogActivity extends Activity {
private static final int PORT = 8765;
private MyHTTPD server;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
try {
server = new MyHTTPD();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected void onPause() {
super.onPause();
if (server != null)
server.stop();
}
public class MyHTTPD extends NanoHTTPD {
public MyHTTPD() throws IOException {
super(PORT, null);
}
public Response serve( String uri, String method, Properties header, Properties parms, Properties files ) {
File rootsd = Environment.getExternalStorageDirectory();
File path = new File(rootsd.getAbsolutePath() + "/samer");
Response r = super.serveFile("/index.htm", header, path, true);
return r;
}
}
}
Looks like a simple fix --- in onResume() you create the server but you still need to call "start()" on it.
Related
I had a question, I built the server part and the client with a socket and did not receive any errors. When I type the local address in the browser, it shows the information in cmd, but when I run the Android application in the emulator or mobile, it does not connect to the server.
The permissions I used:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Server codes:
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
//app.use(express.static(__dirname + '/static')
app.get('/', function (req, res, next) {
res.sendFile(__dirname + '/static/index.html');
});
io.on('connection', function (socket) {
console.log('one user connected ' + socket.id);
socket.on('message',function (data) {
console.log(data);
var sockets=io.sockets.sockets;
sockets.forEach(function (item) {
item.emit('message',{message:data});
});
});
socket.on('disconnect', function (){
console.log('user disconnected');
})
});
http.listen(8000)
console.log('server run on port 8000');
The MainActivity.java is:
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.github.nkzawa.emitter.Emitter;
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URISyntaxException;
public class MainActivity extends AppCompatActivity {
private Socket socket;
{
try {
socket = IO.socket("http://192.168.42.51:8000");
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
Button btnSend;
EditText edtTextMessage;
LinearLayout linearMessage;
LinearLayout.LayoutParams layoutParams;
public Handler handler;
#Override
protected void onDestroy() {
super.onDestroy();
socket.disconnect();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSend = (Button) findViewById(R.id.btnSend);
handler =new Handler();
edtTextMessage = (EditText) findViewById(R.id.edtTextMessage);
linearMessage=(LinearLayout)findViewById(R.id.linearMessage);
socket.connect();
socket.on("message", handlerIncomingMessage);
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String message = edtTextMessage.getText().toString();
sendMessage(message);
}
});
}
public Emitter.Listener handlerIncomingMessage = new Emitter.Listener() {
#Override
public void call(Object... args) {
handler.post(new Runnable() {
#Override
public void run() {
JSONObject jsonObject=(JSONObject)args[0];
String message="";
try {
message=jsonObject.getString("message").toString();
TextView textView=new TextView(getApplicationContext());
textView.setText(message);
textView.setTextSize(18);
layoutParams=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
linearMessage.addView(textView);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
};
private void sendMessage(String message) {
socket.emit("Message", message);
}
}
please guide me.
I had the same issue before, it is because you are running the application on a emulator. Try to run it on a local phone on your local network with the API also running.
In emulator Localhost Ip is :http://10.0.2.2 use it if u are running in localhost.
I'm a beginner and I have been following several tutorials in order to parse JSON. I am just about to compile and try to run for the first time but when I tried to make an object of my java class and have the process run when the button "click" is triggered, I get an error stating " Cannot resolve symbol "fetchData" "
package com.example.h.arbitrage;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
Button click;
public static TextView data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
click = findViewById(R.id.button);
data = findViewById(R.id.fetcheddata);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fetchData process = new fetchData();
((fetchData) process).execute();
}
});
}
}
I'm also including the code for fetchData.java in case there's something in there that's causing this.
I've looked all over for the answer and it might be very obvious but I don't even have the terminology to properly research this...
import android.net.UrlQuerySanitizer;
import android.os.AsyncTask;
import com.example.h.arbitrage.MainActivity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class fetchData extends AsyncTask<Void,Void,Void> {
String data = "";
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("https://");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line ="";
while(line != null){
line = bufferedReader.readLine();
data = data + line;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
MainActivity.data.setText(this.data);
}
}
Thanks in advance for any help.
I am using Windows 7, 64bit and Android Studio.
I am doing two tasks-
Reading data from file in AsyncTaskRunner in doInBackground. Then I am publishing the progress and passing the data.
In progress update, I am reading the data and plotting it to the graph.
I am using GraphView to plot the graph.
Problem- My app freezes after couple of seconds and "Application is not responding" displays.
I am new to android programming, so please guide me.
Here is the code-
package com.example.user.ui_layout;
//import java.util.Random;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.BufferedReader;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.Viewport;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
import com.jjoe64.graphview.GridLabelRenderer;
import android.os.AsyncTask;
import android.graphics.Color;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
//private static final Random RANDOM = new Random();
private LineGraphSeries<DataPoint> series;
private int lastX = 0;
String line;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GraphView graphView = (GraphView) findViewById(R.id.graph);
GridLabelRenderer gridLabelRenderer = graphView.getGridLabelRenderer();
series = new LineGraphSeries<DataPoint>();
series.setColor(Color.RED);
graphView.addSeries(series);
Viewport viewport = graphView.getViewport();
viewport.setScrollable(false);
viewport.setScalable(true);
viewport.setYAxisBoundsManual(true);
viewport.setMinY(-50);
viewport.setMaxY(300);
viewport.setXAxisBoundsManual(true);
viewport.setMinX(0);
viewport.setMaxX(200);
new AsyncTaskRunner().execute("");
}
private class AsyncTaskRunner extends AsyncTask<String, Integer, String>
{
#Override
protected String doInBackground(String... params) {
try {
Thread.sleep(3000); //1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, "demo.txt");
try {
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null)
{
int y = Integer.parseInt(line);
publishProgress(y);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
return line;
}
#Override
protected void onPostExecute(String result)
{
}
#Override
protected void onPreExecute()
{
}
#Override
protected void onProgressUpdate(Integer... s)
{
series.appendData(new DataPoint(lastX++, s[0]), true, 1800);
}
}
}
I'm trying to build an app which will periodically call the Camera to take a picture and save it.
My problem is that unless I put the 'takePictuce' call in the 'onCreate' the response to 'takePicture' (onPictureTaken) is never called.
I've broken down the app as simply as possible to illustrate.
if a class to handle the camera is partially defined as:
public class CameraHandler {
private Camera mCamera;
public CameraHandler(){
mCamera = Camera.open();
mCamera.setPreviewTexture(new SurfaceTexture(10));
mCamera.startPreview();
mCamera.takePicture(null, null, mPicture);
}
Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
} catch (IOException e) { }
}
};
Then when I put the following code into MainActivity.java, 'onPictureTaken' IS called when CameraHandler is instantiated.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CameraHandler cameraHandler = new CameraHandler();
}
However, putting the call to instantiate CameraHandler in a click event in the MainActivity.java will NOT call 'onPictureTaken' in response to the takePicture call.
(This snippet is located in MainACtivity.java)
public void onClickListener(View view){
CameraHandler cameraHandler = new CameraHandler();
}
So why is this occurring, and how can I get the call to take a picture in the class where it belongs and not in the 'main' of the program?
All help welcome
Finally figured out how to set the phone to take timed pics without any screen display.
There were 2 main issues I struggled with. First, I wanted to take the pics without displaying to screen. Along those lines, I found an example where they used :
mCamera.setPreviewTexture(new SurfaceTexture(10));
and nothing showed on the screen when using this preview method. It appears that some sort of preview is required. Another method was to set the preview to 1 pixel. This method had examples online which appeared to work as well, but I did not try it.
The second and bigger problem had to do with 'onPictureTaken' method. This method processes your picture after the 'takePicture' call.
It seemed that no matter what looping method I used, or where in the code the call to 'takePicture' was located, all of the 'onPictureTaken' methods were queued up and called one after another once the parent of the 'takePicture' caller ended.
Although the picture data processed by onPictureTaken were in a proper time sequence, I could see that having several hundred pics stored and waiting to process could cause problems, and a method needed to be found where on pic was processed and stored before the next pic was taken.
Along those lines, I stumbled upon the AlarmManager and coupled that with the BroadcastReceiver and Future classes to solve the problem.
What I've done is set the alarmManger to go off at a set time or time frequency. The BroadcaseReceiver captures this call & in turn calls a method which creates
a thread where a 'Future' object makes the call to take a picture.
'Future' object is nice, because it will wait for the physical camera to take the picture (takePicture) and then process it (onPictureTaken). This all occurs in one thread, then terminates. So no queuing of pics to process and each picture sequence is handled separately.
Code is contained below. Note that some of the default 'Overrides' have been left out to save space. Also, the visible screen was basically a button which captured the click event...very basic.
MainActivity.java:
package myTest.com.test;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class MainActivity extends Activity {
CameraHandler cameraHandler;
public BroadcastReceiver br;
public PendingIntent pi;
public AlarmManager am;
final static private long LOOPTIME = 20000;
private static final ExecutorService threadpool = Executors.newFixedThreadPool(3);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setup();
}
private void setup() {
try{
cameraHandler = new CameraHandler();
br = new BroadcastReceiver() {
#Override
public void onReceive(Context c, Intent i) {
//Toast.makeText(c, "Taking a pic!", Toast.LENGTH_LONG).show();
TryAThread();
}
};
registerReceiver(br, new IntentFilter("com.timedActivity.activity") );
pi = PendingIntent.getBroadcast(this, 0, new Intent("com.timedActivity.activity"), 0);
am = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
}
catch (Exception e){ }
}
private void TryAThread() {
try{
CameraCaller cameraCaller = new CameraCaller(cameraHandler);
Future future = threadpool.submit(cameraCaller);
while (!future.isDone()) {
try {
Thread.sleep(5000);
} catch (Exception ex) { }
}
}
catch (Exception e){ }
}
#Override
protected void onDestroy() {
am.cancel(pi);
unregisterReceiver(br);
super.onDestroy();
}
public void onClickListener(View view){
try{
am.setRepeating(am.ELAPSED_REALTIME,SystemClock.elapsedRealtime(), LOOPTIME, pi);
}
catch (Exception e){ }
}
}
CameraCaller.java:.
package myTest.com.test;
import java.util.concurrent.Callable;
public class CameraCaller implements Callable {
private CameraHandler cameraHandler;
public CameraCaller(CameraHandler ch){
cameraHandler = ch;
}
#Override
public Object call() throws Exception {
cameraHandler.takeAPic();
return true;
}
}
CameraHandler.java:.
package myTest.com.test;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.os.Environment;
import android.util.Log;
import junit.runner.Version;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CameraHandler implements Camera.PictureCallback{
private Camera mCamera;
public CameraHandler(){
}
public Boolean takeAPic(){
try{
if (mCamera == null){
mCamera = Camera.open();
mCamera.enableShutterSound(false);
try {
mCamera.setPreviewTexture(new SurfaceTexture(10));
}
catch (IOException e1) {Log.e(Version.id(), e1.getMessage());
}
}
mCamera.startPreview();
mCamera.takePicture(null, null, this);
}
catch (Exception ex){ }
return true;
}
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
} catch (IOException e) { }
try {
Thread.sleep(2000);
}catch (Exception ex){}
}
public static File getOutputMediaFile() {
File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File mediaStorageDir = new File(file, "MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
return mediaFile;
}
}
Here is my Android Media player code. I don't know what I am missing in this code, when I run with breakpoint at line MediaPlayer mp = new MediaPlayer() in Debug mode. All the files in zip folder is played. But when I run the application in normal mode the first file is played and then I get this error:
android.app.SuperNotCalledException: Activity {com.example.mediaplayer/com.example.mediaplayer.MainActivity} did not call through to super.onCreate()
Code:
package com.example.mediaplayer;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.commons.io.IOUtils;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.Button;
public class MainActivity extends Activity {
private MediaPlayer mp;
private static final String MAIN_TAG ="ERROR";
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
//final String file_loc= Environment.getExternalStorageDirectory().toString();
//Log.i("location",file_loc);
ZipFile zip = new ZipFile("/storage/emulated/0/AjeshDocument/sample.zip");
for(int i=1;i<7;i++){
ZipEntry entry = zip.getEntry("sample/rihanna_"+i+".mp3");
if (entry != null) {
InputStream in = zip.getInputStream(entry);
// see Note #3.
File tempFile = File.createTempFile("_AUDIO_", ".wav");
FileOutputStream out = new FileOutputStream(tempFile);
IOUtils.copy(in, out);
// do something with tempFile (like play it)
File f = tempFile;
try {
if (f.exists())
{
Log.i(MAIN_TAG,"Audio file found!");
MediaPlayer mp = new MediaPlayer();
FileInputStream fis = new FileInputStream(f);
mp.setDataSource(fis.getFD());
mp.prepare();
//mp.setLooping(false);
mp.start();
//mp.stop();
// mp.release();
Log.i(MAIN_TAG,"Pronounciation finished!");
}
else
{
Log.i(MAIN_TAG,"File doesn't exist!!");
}
}
catch (IOException e)
{
Log.i(MAIN_TAG,e.toString());
}
}
else {
// no such entry in the zip
}
} //for end
mp.release();
}
catch (Exception e) {
// handle your exception cases...
Log.i(MAIN_TAG,e.toString());
}
}
#Override
protected void onResume() {
Log.w("Info", "App Resume");
super.onResume();
}
#Override
protected void onStop() {
Log.w("Info", "App stopped");
super.onStop();
}
#Override
protected void onDestroy() {
Log.w("Info", "App destoryed");
super.onDestroy();
}
}
You didn't call the Activity's onCreate() method, i.e the super class' one. Add the call to MainActivity's onCreate() method:
public class MainActivity extends Activity {
private MediaPlayer mp;
private static final String MAIN_TAG ="ERROR";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // this line is missing
// your code below ...