[Q] Alternative to using KSOAP for accessing WebService from Android application - Android Software Development

Hi,
I am adding ksoap2-j2se-full-2.1.2.jar as external jar into Android project & accessing the SOAP API to access .NET webservices from Android application. The size of the ksoap2-j2se-full-2.1.2.jar is 96 KB & so I dont want to increase the size of the Android application by using the external jar.
Kindly provide an alternate option by which we can access the .NET webservice from Android application so that the size of the Android application get reduced.
Warm Regards,
Chiranjib

Use REST instead of web services. Its faster than using Web Services. .NET 3.5 SP1 + 4.0 both support rest. Here is a quick VB Console application that creates a RESTful web service:
(btw - its just a test, nothing pretty)
Imports System
Imports System.ServiceModel
Imports System.ServiceModel.Description
Module Program
Private _WS As servicehost
Sub Main()
Dim _uri As New Uri("http://" + Environment.MachineName + ":81/Pool")
_WS = New ServiceHost(GetType(WCF), _uri)
Dim ep As ServiceEndpoint = _WS.AddServiceEndpoint(GetType(WCF), New WebHttpBinding, String.Empty)
ep.Behaviors.Add(New WebHttpBehavior)
_WS.Open()
Console.WriteLine("Ready")
Console.Read()
End Sub
Imports System.ServiceModel
Imports System.ServiceModel.Channels
Imports System.ServiceModel.Web
<ServiceContract()> _
Public Class WCF
<OperationContract()> _
<WebGet(RequestFormat:=WebMessageFormat.Json, UriTemplate:="add&a={A1}&b={B1}")> _
Public Function Add(ByVal A1 As String, ByVal B1 As String) As Integer
Return A1 + B1
End Function
End Class
Then you can access the web service using IE or Chrome:
http://localhost:81/pool/add&a=5&b=10
You can them implement this in Android using something like this:
package com.carstendressler.pool;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class RestClient {
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
/* This is a test function which will connects to a given
* rest service and prints it's response to Android Log with
* labels "Praeda".
*/
public static void connect(String url)
{
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Examine the response status
Log.i("Praeda",response.getStatusLine().toString());
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
Log.i("Praeda",result);
// A Simple JSONObject Creation
JSONObject json=new JSONObject(result);
Log.i("Praeda","<jsonobject>\n"+json.toString()+"\n</jsonobject>");
// A Simple JSONObject Parsing
JSONArray nameArray=json.names();
JSONArray valArray=json.toJSONArray(nameArray);
for(int i=0;i<valArray.length();i++)
{
Log.i("Praeda","<jsonname"+i+">\n"+nameArray.getString(i)+"\n</jsonname"+i+">\n"
+"<jsonvalue"+i+">\n"+valArray.getString(i)+"\n</jsonvalue"+i+">");
}
// A Simple JSONObject Value Pushing
json.put("sample key", "sample value");
Log.i("Praeda","<jsonobject>\n"+json.toString()+"\n</jsonobject>");
// Closing the input stream will trigger connection release
instream.close();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
BTW - this isnt my code. I took it from various web sites...

Related

[Help]Create App

Hi Guys,
I open this thread because I need help:I would like to create an app which do a login on a website(my website)...any suggest?I'm a noob D:... ty
Try going through this tutorial
http://www.edumobile.org/android/android-development/login-request-example-in-android/
Ty so much for your answer but it helps me only at 50% ,because I would like this app connect to my website...at the moment it compare user and password insert ty to this function:
if((txtUserName.getText().toString()).equals(txtPassword.getText().toString())){
Toast.makeText(LoginRequestExample.this, "Login Successful",Toast.LENGTH_LONG).show();
} else{
Toast.makeText(LoginRequestExample.this, "Invalid Login",Toast.LENGTH_LONG).show();
}
What do I have to modify for making it compare user and password on mine online database?
ultimatexemnas said:
Ty so much for your answer but it helps me only at 50% ,because I would like this app connect to my website...at the moment it compare user and password insert ty to this function:
if((txtUserName.getText().toString()).equals(txtPassword.getText().toString())){
Toast.makeText(LoginRequestExample.this, "Login Successful",Toast.LENGTH_LONG).show();
} else{
Toast.makeText(LoginRequestExample.this, "Invalid Login",Toast.LENGTH_LONG).show();
}
What do I have to modify for making it compare user and password on mine online database?
Click to expand...
Click to collapse
I use this two methods to log on the internet. As you understand downloadUrl(URL); gives you what site tells you. I can recommend you to use special URLs in order to log in(for example example.com/auth.php?req=login&pass=....&login=....)
Code:
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
//int response = conn.getResponseCode();
//Log.d("NaviLogin", "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
Ty for you answer.
I have a noobish answer(another xD):have I to replace all myurl with the url of my website,right?>.<
ultimatexemnas said:
Ty for you answer.
I have a noobish answer(another xD):have I to replace all myurl with the url of my website,right?>.<
Click to expand...
Click to collapse
URL of your site with sonething containig your password and login and server should give you answer if your pass and login are in database or not
So,in the end it should be something like this?
package com.example.LoginRequestExample;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginRequestExample extends Activity {
EditText txtUserName;
EditText txtPassword;
Button btnLogin;
Button btnCancel; 
 @override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_request_example);
txtUserName=(EditText)this.findViewById(R.id.txtUname);
txtPassword=(EditText)this.findViewById(R.id.txtPwd);
btnLogin=(Button)this.findViewById(R.id.btnLogin);
btnLogin=(Button)this.findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if ((private String downloadUrl(String mywebsite.ukcom) throws IOException {
InputStream is = null;
int len = 500;
try {
URL url = new URL mywebsite.ukcom);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
//int response = conn.getResponseCode();
//Log.d("NaviLogin", "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
{
Toast.makeText(LoginRequestExample.this, "Invalid Login",Toast.LENGTH_LONG).show();
}
}
);
}}
Right?Are there any errors?
I've clean it up for you.
Replace google.com with your website.
Make sure your website takes username and password as a GET input.
The variable responseContent takes the result of the website after login in.
Code:
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginRequestExample extends Activity {
EditText txtUserName;
EditText txtPassword;
Button btnLogin;
Button btnCancel;
String username, password, responseContent;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_request_example);
txtUserName = (EditText) this.findViewById(R.id.txtUname);
txtPassword = (EditText) this.findViewById(R.id.txtPwd);
btnLogin = (Button) this.findViewById(R.id.btnLogin);
btnLogin = (Button) this.findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
if (txtPassword.getText().toString().trim().length() < 1
|| txtUserName.getText().toString().trim().length() < 1) {
Toast.makeText(LoginRequestExample.this,
"Please enter your login details",
Toast.LENGTH_SHORT).show();
} else {
username = txtUserName.getText().toString().trim();
password = txtPassword.getText().toString().trim();
downloadUrl("http://google.com/login.php?u=" + username + "&password=" + password);
}
}
});
}
private void downloadUrl(String myurl) throws IOException {
InputStream is = null;
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
// int response = conn.getResponseCode();
// Log.d("NaviLogin", "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
responseContent = contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
public String readIt(InputStream stream, int len) throws IOException,
UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
}

Accelerometer Data

I have the code below created but I can not for the life of me figure out how I can send data from the accelerator. I need it to send a constant stream of data until I turn it off. I can't even figure out how to cast the data to a proper variable. Any suggestion would be greatly appreciated.
Code:
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements SensorEventListener
{
private static final String TAG = "bluetooth1";
Sensor accelerometer;
SensorManager sm;
TextView acceleration;
Button on, off;
float values;
TelephonyManager tManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String uuid = tManager.getDeviceId();
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
// SPP UUID service
private UUID MY_UUID = UUID
.fromString(uuid);
// MAC-address of Bluetooth module (you must edit this line)
private static String address = "B0:C4:E7:CF:19:6E";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
accelerometer = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sm.registerListener(this, accelerometer,
SensorManager.SENSOR_DELAY_NORMAL);
acceleration = (TextView) findViewById(R.id.accelText);
off = (Button) findViewById(R.id.bOff);
on = (Button) findViewById(R.id.bOn);
btAdapter = BluetoothAdapter.getDefaultAdapter();
checkBTState();
// On click Listeners
off.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
sendData("a");
Toast.makeText(getBaseContext(), "Turn on LED",
Toast.LENGTH_SHORT).show();
}
});
on.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
sendData("a");
Toast.makeText(getBaseContext(), "Turn on LED",
Toast.LENGTH_SHORT).show();
}
});
// End Onclick Listeners
private BluetoothSocket createBluetoothSocket(BluetoothDevice device)
throws IOException
{
if (Build.VERSION.SDK_INT >= 10)
{
try
{
final Method m = device.getClass().getMethod(
"createInsecureRfcommSocketToServiceRecord",
new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, MY_UUID);
} catch (Exception e)
{
Log.e(TAG, "Could not create Insecure RFComm Connection", e);
}
}
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
@Override
public void onResume()
{
super.onResume();
Log.d(TAG, "...onResume - try connect...");
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the
// UUID for SPP.
try
{
btSocket = createBluetoothSocket(device);
} catch (IOException e1)
{
errorExit("Fatal Error", "In onResume() and socket create failed: "
+ e1.getMessage() + ".");
}
// Discovery is resource intensive. Make sure it isn't going on
// when you attempt to connect and pass your message.
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Log.d(TAG, "...Connecting...");
try
{
btSocket.connect();
Log.d(TAG, "...Connection ok...");
} catch (IOException e)
{
try
{
btSocket.close();
} catch (IOException e2)
{
errorExit("Fatal Error",
"In onResume() and unable to close socket during connection failure"
+ e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
Log.d(TAG, "...Create Socket...");
try
{
outStream = btSocket.getOutputStream();
} catch (IOException e)
{
errorExit(
"Fatal Error",
"In onResume() and output stream creation failed:"
+ e.getMessage() + ".");
}
}
@Override
public void onPause()
{
super.onPause();
Log.d(TAG, "...In onPause()...");
if (outStream != null)
{
try
{
outStream.flush();
} catch (IOException e)
{
errorExit(
"Fatal Error",
"In onPause() and failed to flush output stream: "
+ e.getMessage() + ".");
}
}
try
{
btSocket.close();
} catch (IOException e2)
{
errorExit("Fatal Error", "In onPause() and failed to close socket."
+ e2.getMessage() + ".");
}
}
private void checkBTState()
{
// Check for Bluetooth support and then check to make sure it is turned
// on
// Emulator doesn't support Bluetooth and will return null
if (btAdapter == null)
{
errorExit("Fatal Error", "Bluetooth not supported");
} else
{
if (btAdapter.isEnabled())
{
Log.d(TAG, "...Bluetooth ON...");
} else
{
// Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
private void errorExit(String title, String message)
{
Toast.makeText(getBaseContext(), title + " - " + message,
Toast.LENGTH_LONG).show();
finish();
}
private void sendData(String message)
{
byte[] msgBuffer = message.getBytes();
Log.d(TAG, "...Send data: " + message + "...");
try
{
outStream.write(msgBuffer);
} catch (IOException e)
{
String msg = "In onResume() and an exception occurred during write: "
+ e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg
+ ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 35 in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString()
+ " exists on server.\n\n";
errorExit("Fatal Error", msg);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event)
{
// TODO Auto-generated method stub
acceleration.setText("x: " + event.values[0] + "\nY:" + event.values[1]
+ "\nZ:" + event.values[2]);
}
}
NoiseAgent said:
I can not for the life of me figure out how I can send data from the accelerator.
Click to expand...
Click to collapse
What's your exact problem? You're getting the data from the accelerator in the onSensorChanged()-Method, so you just need to send them there.
Reply
EmptinessFiller said:
What's your exact problem? You're getting the data from the accelerator in the onSensorChanged()-Method, so you just need to send them there.
Click to expand...
Click to collapse
My problem is I am unsure how to send it. How do you actually do that? I don't know what the syntax is to transmit data over bluetooth. The sendData wont work it gives me the error sendData(String) in the type MainActivity is not applicable for the arguments(Sensor)
Use DataOutputStream and DataInputStream to send/read the three float-values: DataOutputStream#writeFloat(event.values[0/1/2]);
EmptinessFiller said:
Use DataOutputStream and DataInputStream to send/read the three float-values: DataOutputStream#writeFloat(event.values[0/1/2]);
Click to expand...
Click to collapse
Sweet baby jesus, lord all mighty, thank you.
When I add that to the onSensorChanged I get the error "Cannot make a static reference to the non-static method writeFloat(float) from
the type DataOutputStream" not sure how to clear it up.
Also, I have jumped in way over my head, I really just want to wrap this last bit up and start from scratch. If anyone has a good resource for learning object oriented Java programming and would like to share, that would just be the bees-knees.
Of course java/object oriented programming is necessary.
You have to create an object from the ObjectOutputStream like
ObjectOutputStream oos = new ObjectOutputStream(...);
oos.writeFloat(...);
...

Face Detection in Background Service

I am making an android app which requires to capture image using front camera using android service. Also we need to detect face in the image so obtained. But when calling the detectfaces() function, the app unfortuantely stops. I am posting the code for it here. Please help me find out where i am going wrong.
here is my code..!!!!
package com.android.camerarecorder;
import android.app.Activity;
import android.content.Intent;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class CameraRecorder extends Activity implements SurfaceHolder.Callback {
static final int MAX_FACES = 5;
//private static final String TAG = "Recorder";
public static SurfaceView mSurfaceView;
public static SurfaceHolder mSurfaceHolder;
public static Camera mCamera;
public static boolean mPreviewRunning;
public static TextView jpgName;
public static ImageView jpgView;
public static ImageView imageView;
/** Called when the activity is first created. */
@SuppressWarnings("deprecation")
 @override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imageView = (ImageView)findViewById(R.id.jpgview);
mSurfaceView = (SurfaceView) findViewById(R.id.surfaceView1);
jpgName = (TextView)findViewById(R.id.jpgname);
jpgView = (ImageView)findViewById(R.id.jpgview);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
Button btnStart = (Button) findViewById(R.id.StartService);
btnStart.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(CameraRecorder.this,RecorderService.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startService(intent);
//finish();
}
});
Button btnStop = (Button) findViewById(R.id.StopService);
btnStop.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
stopService(new Intent(CameraRecorder.this, RecorderService.class));
}
});
}
@override
public void surfaceCreated(SurfaceHolder holder) {
}
@override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
}
The above code was the activity where the service is called. The service is as follows:
package com.android.camerarecorder;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.iutputStream;
import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Parameters;
import android.media.AudioManager;
import android.media.FaceDetector;
import android.media.FaceDetector.Face;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class RecorderService extends Service
{
private SurfaceHolder sHolder;
private TextView mjpgname;
private ImageView mjpgview;
private ImageView mimageview;
Bitmap bm;
Bundle bundle = new Bundle();
String filename;
private int cameraId = 0;
//a variable to control the camera
private Camera mCamera;
final static String DEBUG_TAG = "Test";
Uri imageFileUri;
//the camera parameters
private Parameters parameters;
/** Called when the activity is first created. */
@override
public void onCreate()
{
super.onCreate();
sHolder=CameraRecorder.mSurfaceHolder;
mCamera = CameraRecorder.mCamera;
mjpgname= CameraRecorder.jpgName;
mjpgview = CameraRecorder.jpgView;
mimageview=CameraRecorder.imageView;
}
@SuppressWarnings("deprecation")
 @override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
// do we have a camera?
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Toast.makeText(this, "No camera on this device", Toast.LENGTH_LONG).show();
} else {
cameraId = findFrontFacingCamera();
if (cameraId < 0) {
Toast.makeText(this, "No front facing camera found.",Toast.LENGTH_LONG).show();
} else {
mCamera = Camera.open(cameraId);
}
}
//mCamera = Camera.open();
SurfaceView sv = new SurfaceView(getApplicationContext());
sv=CameraRecorder.mSurfaceView ;
try {
mCamera.setPreviewDisplay(sHolder);
parameters = mCamera.getParameters();
//set camera parameters
mCamera.setParameters(parameters);
mCamera.startPreview();
mCamera.takePicture(null, null, mCall);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Get a surface
sHolder = sv.getHolder();
//tells Android that this surface will have its data constantly replaced
sHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
private int findFrontFacingCamera() {
int cameraId = -1;
// Search for the front facing camera
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
Log.d(DEBUG_TAG, "Camera found");
cameraId = i;
break;
}
}
return cameraId;
// TODO Auto-generated method stub
}
Camera.PictureCallback mCall = new Camera.PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera)
{
//decode the data obtained by the camera into a Bitmap
// FileOutputStream outStream = null;
try{
imageFileUri = getContentResolver().insert(
Media.EXTERNAL_CONTENT_URI, new ContentValues());
OutputStream imageFileOS = getContentResolver().openOutputStream(
imageFileUri);
imageFileOS.write(data);
imageFileOS.flush();
imageFileOS.close();
filename = getRealPathFromURI(imageFileUri);
File imgFile = new File(filename);
if(imgFile.exists())
{
bm = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
mjpgview.setImageBitmap(bm);
}
detectFaces();
// mjpgname.setText("success");
/*
Intent i = new Intent(RecorderService.this, FaceDetect.class);
//Add your data to bundle
bundle.putString("Filepath", filename) ;
//Add the bundle to the intent
i.putExtras(bundle);
//Fire that second activity
startActivity(i);*/
/* final File images = Environment.getExternalStorageDirectory();
String filePath = "magic";
String final_path = images+"/"+filePath;
outStream = new FileOutputStream(final_path);
outStream.write(data);
outStream.close();*/
} catch (FileNotFoundException e){
Log.d("CAMERA", e.getMessage());
} catch (IOException e){
Log.d("CAMERA", e.getMessage());
}
}
};
private void detectFaces() {
if(null != bm){
int width = bm.getWidth();
int height = bm.getHeight();
FaceDetector detector = new FaceDetector(width, height,CameraRecorder.MAX_FACES);
Face[] faces = new Face[CameraRecorder.MAX_FACES];
Bitmap bitmap565 = Bitmap.createBitmap(width, height, Config.RGB_565);
Paint ditherPaint = new Paint();
Paint drawPaint = new Paint();
ditherPaint.setDither(true);
drawPaint.setColor(Color.RED);
drawPaint.setStyle(Paint.Style.STROKE);
drawPaint.setStrokeWidth(2);
Canvas canvas = new Canvas();
canvas.setBitmap(bitmap565);
//canvas.setBitmap(cameraBitmap);
canvas.drawBitmap(bm, 0, 0, ditherPaint);
int facesFound = detector.findFaces(bitmap565, faces);
// int facesFound = detector.findFaces(cameraBitmap, faces);
PointF midPoint = new PointF();
float eyeDistance = 0.0f;
float confidence = 0.0f;
Log.i("FaceDetector", "Number of faces found: " + facesFound);
if(facesFound > 0)
{
for(int index=0; index<facesFound; ++index){
faces[index].getMidPoint(midPoint);
eyeDistance = faces[index].eyesDistance();
confidence = faces[index].confidence();
Log.i("FaceDetector",
"Confidence: " + confidence +
", Eye distance: " + eyeDistance +
", Mid Point: (" + midPoint.x + ", " + midPoint.y + ")");
canvas.drawRect((int)midPoint.x - eyeDistance ,
(int)midPoint.y - eyeDistance ,
(int)midPoint.x + eyeDistance,
(int)midPoint.y + eyeDistance, drawPaint);
}
}
// Camera_timer.key = eyeDistance;
// tv.setText(eyeDistance+"");
String filepath = Environment.getExternalStorageDirectory()
+ "/facedetect" +System.currentTimeMillis() + ".jpg";
try {
FileOutputStream fos = new FileOutputStream(filepath);
bitmap565.compress(CompressFormat.JPEG, 90, fos);
// cameraBitmap.compress(CompressFormat.JPEG, 90, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
mimageview.setImageBitmap(bitmap565);
// imageView.setImageBitmap(cameraBitmap);
}
}
private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
//This method was deprecated in API level 11
//Cursor cursor = managedQuery(contentUri, proj, null, null, null);
CursorLoader cursorLoader = new CursorLoader((Context) mCall,contentUri, proj, null, null,null);
Cursor cursor = cursorLoader.loadInBackground();
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
// TODO Auto-generated method stub
}
@override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}

[Q] Code placement for writing TCP/IP data to TextView

Hello,
I am a first time poster new to Android app development so please bear with me. I am currently working off of two great TCP/IP Client examples. My goal is to create a simple TCP/IP Client that connects to a server and, once a connection is established, continuously updates a TextView with strings passed from the server. If the user presses a button, the client sends a stop command to the server and I would ultimately like to expand the TextView into a graph with the converted string values. I am able to establish the connection to the server and send the stop command from the client but my attempts at adding the read capability have, so far, been unsuccessful with the app crashing as soon as it starts up.
Since it is my first time posting, I am not allowed to link the examples I am using. If anyone is interested in seeing them, however, they are posts from the android-er blog titled: "Android Server/Client example - client side using Socket" and "Bi-directional communication between Client and Server, using ServerSocket, Socket, DataInputStream and DataOutputStream".
Here is the code in my MainActivity:
Code:
package com.example.androidclient;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
TextView textResponse;
TextView textIn;
EditText editTextAddress, editTextPort;
Button buttonConnect, buttonStopTest, buttonDisconnect;
Socket socket = null;
DataInputStream incomingString = null;
DataOutputStream terminalLetter = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
editTextAddress = (EditText)findViewById(R.id.address);
editTextPort = (EditText)findViewById(R.id.port);
buttonConnect = (Button)findViewById(R.id.connect);
buttonDisconnect = (Button)findViewById(R.id.disconnect);
buttonStopTest = (Button)findViewById(R.id.stop_test);
textResponse = (TextView)findViewById(R.id.response);
textIn = (TextView)findViewById(R.id.text_in);
buttonConnect.setOnClickListener(buttonConnectOnClickListener);
buttonStopTest.setOnClickListener(buttonStopTestOnClickListener);
buttonDisconnect.setOnClickListener(buttonDisconnectOnClickListener);
}
OnClickListener buttonConnectOnClickListener = new OnClickListener(){
//setOnClickListener sets a callback to be invoked when the button is clicked
@Override
public void onClick(View arg0) {
//Clicking button (Connect) calls a MyClientTask defined below.
MyClientTask myClientTask = new
MyClientTask(editTextAddress.getText().toString(),
Integer.parseInt(editTextPort.getText().toString()));
myClientTask.execute();
}
};
OnClickListener buttonStopTestOnClickListener = new OnClickListener(){
//setOnClickListener sets a callback to be invoked when the button is clicked
@Override
public void onClick(View arg0) {
try {
terminalLetter = new DataOutputStream(socket.getOutputStream());
terminalLetter.writeByte('b');
terminalLetter.writeByte('\n');
terminalLetter.close();
socket.close();
}
catch (IOException e) {
System.err.println("Couldn't get I/O for the connection.");
}
}
};
OnClickListener buttonDisconnectOnClickListener = new OnClickListener(){
//setOnClickListener sets a callback to be invoked when the button is clicked
@Override
public void onClick(View arg0) {
try {
socket.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
public class MyClientTask extends AsyncTask<Void, Void, Void> {
String IPaddress;
int Port;
String response = "";
MyClientTask(String addr, int port){
IPaddress = addr;
Port = port;
}
@Override
protected Void doInBackground(Void... arg0) {
//Took socket declaration from here.
try {
//Taking relevant parameters and applying them to socket
socket = new Socket(IPaddress, Port);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
incomingString = new DataInputStream(socket.getInputStream());
textIn.setText(incomingString.readUTF());
/*
* notice:
* inputStream.read() will block if no data return
*/
while ((bytesRead = inputStream.read(buffer)) != -1){
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
}
catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}
finally{
if(socket != null){
try {
socket.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
@Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
}
}
I put the commands for reading data from the server and writing it to the TextView with the code that sets up the connection to the socket. The idea was that it would be the next step after the connection is established but I realize that it looks like I am only reading once. I tried adding a while loop and bringing it out of the doInBackground. In each case, all I got was the whole app crashing on me. It looks fairly straight forward in the example but there the connection is automatic, not triggered and I have not been able to modify the code successfully.
I am still new to Android and this feels like it is an important part of app development so I am hoping someone in the community can help me understand where the section of code relevant to reading data (continuously) should be placed in relation to the rest.
Best,
Yusif Nurizade
P.S. I was going to include the fragment but, since the post is long enough, I chose to omit it. I can share upon request and the logcat.

[Q] How to pass image from one intent to another

Hi friends,
Here is my code for displaying details and images from MySQL database,All i want to do is pass the detail with image to other inner page through intent.Please help me im new in android.
Activity 1
Code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.ActionBar.LayoutParams;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
@SuppressLint("NewApi") public class News_events extends Fragment {
private String jsonResult;
private String url = "<URL PHP FILES>";
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
ImageView img;
Bitmap bitmap;
ProgressDialog pDialog;
// alert dialog manager
AlertDialogManager alert = new AlertDialogManager();
// Internet detector
ConnectionDetector cd;
InputStream is=null;
String result=null;
String line=null;
int code;
public News_events(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
pDialog = new ProgressDialog(getActivity());
View rootView = inflater.inflate(R.layout.fragment_news_events, container, false);
cd = new ConnectionDetector(rootView.getContext());
// Check if Internet present
if (!cd.isConnectingToInternet()) {
// Internet Connection is not present
alert.showAlertDialog(getActivity(),
"Internet Connection Error",
"Please connect to working Internet connection", false);
// stop executing code by return
//return.rootView;
return rootView;
}
accessWebService();
return rootView;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getActivity().getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
@Override
protected void onPostExecute(String result) {
display();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void display() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("news_details");
LinearLayout MainLL= (LinearLayout)getActivity().findViewById(R.id.newslayout);
//LinearLayout headLN=(LinearLayout)findViewById(R.id.headsection);
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
final String head = jsonChildNode.optString("title");
final String details = jsonChildNode.optString("text");
final String date = jsonChildNode.optString("date");
final String image = jsonChildNode.optString("img");
//final String time = jsonChildNode.optString("time");
//img = new ImageView(this.getActivity());
//new LoadImage().execute("<URL IMAGE FOLDER>"+image);
img = new ImageView(this.getActivity());
LoadImage ldimg=new LoadImage();
ldimg.setImage(img);
ldimg.execute("<URL IMAGE FOLDER>"+image);
TextView headln = new TextView(this.getActivity());
headln.setText(head); // News Headlines
headln.setTextSize(16);
headln.setTextColor(Color.BLACK);
headln.setGravity(Gravity.CENTER);
headln.setBackgroundColor(Color.parseColor("#ffcd14"));
// headln.setBackgroundResource(R.drawable.menubg);
headln.setPadding(0, 20, 0, 0);
// headln.setHeight(50);
headln.setClickable(true);
TextView dateln = new TextView(this.getActivity());
dateln.setText(date); // News Headlines
dateln.setTextSize(12);
dateln.setTextColor(Color.BLACK);
dateln.setGravity(Gravity.RIGHT);
//dateln.setBackgroundColor(Color.parseColor("#f20056"));
dateln.setBackgroundColor(0x00000000);
dateln.setPadding(0, 0, 10, 10);
dateln.setWidth(100);
dateln.setClickable(true);
View sep=new View(this.getActivity());
sep.setBackgroundColor(Color.parseColor("#252525"));
sep.setMinimumHeight(10);
TextView detailsln = new TextView(this.getActivity());
detailsln.setText(details); // News Details
detailsln.setTextSize(12);
detailsln.setTextColor(Color.BLACK);
detailsln.setGravity(Gravity.CENTER);
detailsln.setPadding(10, 10, 10, 10);
int width = LayoutParams.WRAP_CONTENT;
int height = 200;
LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(width,height);
img.setLayoutParams(parms);
parms.gravity = Gravity.CENTER;
img.setPaddingRelative (15, 15, 15, 15);
MainLL.addView(headln);
MainLL.addView(dateln);
// MainLL.addView(photo);
MainLL.addView(img);
MainLL.addView(detailsln);
MainLL.addView(sep);
img.setClickable(true);
headln.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Toast.makeText(getBaseContext(), head, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity().getApplicationContext(),InnerNewsAndEvents.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
intent.putExtra("img",img.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
dateln.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(),InnerNewsAndEvents.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
intent.putExtra("img",img.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
img.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity().getApplicationContext(),InnerNewsAndEvents.class);
intent.putExtra("head",head.toString());
intent.putExtra("details",details.toString());
intent.putExtra("date",date.toString());
intent.putExtra("img",img.toString());
// intent.putExtra("time",time.toString());
startActivity(intent);
}
});
}
} catch (JSONException e) {
Toast.makeText(getActivity().getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
ImageView img;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.setMessage("Loading Image ....");
pDialog.show();
}
public void setImage(ImageView img ){
this.img=img;
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).openStream());
}
catch (Exception e) { e.printStackTrace(); }
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
img.setImageBitmap(image);
pDialog.dismiss();
}
pDialog.dismiss();
}
}
public static boolean isInternetReachable()
{
try {
//make a URL to a known source
URL url = new URL("google");
//open a connection to that source
HttpURLConnection urlConnect = (HttpURLConnection)url.openConnection();
//trying to retrieve data from the source. If there
//is no connection, this line will fail
Object objData = urlConnect.getContent();
} catch (UnknownHostException e) {
e.printStackTrace();
return false;
}
catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
}
Activity 2
Code:
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
public class InnerNewsAndEvents extends Activity {
ProgressDialog pDialog;
ProgressDialog dialog = null;
Bitmap bitmap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inner_news_and_events);
TextView title=(TextView)findViewById(R.id.tvtitle);
TextView details=(TextView)findViewById(R.id.tvdetails);
ImageView img=(ImageView)findViewById(R.id.imgpic);
Intent intent = getIntent();
String strhead = intent.getStringExtra("head");
String strdetails = intent.getStringExtra("details");
String strdate = intent.getStringExtra("date");
String strimg = intent.getStringExtra("img");
title.setText(strhead);
details.setText(strdetails);
}
}
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
public class InnerNewsAndEvents extends Activity {
ProgressDialog pDialog;
ProgressDialog dialog = null;
Bitmap bitmap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inner_news_and_events);
TextView title=(TextView)findViewById(R.id.tvtitle);
TextView details=(TextView)findViewById(R.id.tvdetails);
ImageView img=(ImageView)findViewById(R.id.imgpic);
Intent intent = getIntent();
String strhead = intent.getStringExtra("head");
String strdetails = intent.getStringExtra("details");
String strdate = intent.getStringExtra("date");
String strimg = intent.getStringExtra("img");
title.setText(strhead);
details.setText(strdetails);
}
}

Categories

Resources