how to use cloudsight api in android app for image recognition - android

public class MainActivity extends AppCompatActivity {
private static final String API_KEY = "b8fo0q33XyuCTm0qbr6XCg";
static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
static final JsonFactory JSON_FACTORY = new JacksonFactory();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button myBtn = (Button) findViewById(R.id.button);
TextView t=(TextView) findViewById(R.id.text);
}
public void onClick(View v) {
try {
CSApi api = new CSApi(
HTTP_TRANSPORT,
JSON_FACTORY,
API_KEY
);
CSPostConfig imageToPost = CSPostConfig.newBuilder()
.withRemoteImageUrl("https://questions4thoughts.files.wordpress.com/2008/11/50rupees.png")
.build();
CSPostResult portResult = api.postImage(imageToPost);
System.out.println("Post result: " + portResult);
try{
Thread.sleep(30000);
CSGetResult scoredResult = api.getImage(portResult);
// t.setText(scoredResult);
}
catch (InterruptedException e){
e.getCause();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
i am new to this api. i have post and get files also i dont know how to use it. when i am running the app it says unfortunately stop. i have used cloudsight api but there no source for using it. Can u suggest some solution on how to use it or some other free api for image recognition.

Did you try giving internet permission above the application tag in Manifest.xml?
if not, add the following line :
<uses-permission android:name="android.permission.INTERNET" />

i've the same issue, few time ago. And i did it :
new Thread() {
#Override
public void run() {
//your code here
}
}.start();
it works perfect, so i share it to you. but for the first time you will received status "not completed", because cloudsight needs 6-12 second until complete. so try to run the thread until you get status complete. Hope you success. :)

Related

time out issues with Android Multicast

I am working on an Android app that will receive multicast packets from a network that already outputs reliable multicast data on 239.255.x.x . I have verified that my device can receive multicast with another application. I'm new to Java and Android but I did confirm that my original code to gather the Multicast info worked in a java application and have been struggling to get everything working in the Android side of things. I have permissions set in the manifest,
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
the networking portion of code runs in an Asynctask as to not crash the app but my Multicast.receive() calls all result in a time out.Is there something else I am missing or something that prevents multicast sockets from working in the asynctask class?
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new getACN.execute();
}
});
}
public class getACN extends AsyncTask<Void, Void, String> {
#Override
public String doInBackground(Void... Void) {
byte[] buf = new byte[1000];
try {
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
MulticastLock multicastLock = wifiManager.createMulticastLock("sACN");
multicastLock.acquire();
InetAddress group = InetAddress.getByName("239.255.0.3");
DatagramPacket recv = new DatagramPacket(buf,buf.length);
MulticastSocket sock = new MulticastSocket(5568);
sock.joinGroup(group);
sock.setSoTimeout(1000);
sock.receive(recv);
sock.leaveGroup(group);
} catch (IOException e) {
return e.getMessage();
} catch (SecurityException e) {
return e.getMessage();
}
return Arrays.toString(buf);
}
#Override
protected void onPostExecute(String result){
TextView textView = (TextView) findViewById(R.id.text01);
textView.setText(result);
}
}
}

Using Google Drive to backup and restore SQLite Database

I've managed to create a backup of my database on an SD card and restore from there but realized that the purpose of my backup is to ensure the safety of the data and in this case if the physical device itself is damaged, lost, or spontaneously combusts so will the backup on the SD card. So having the backup in the same place as the original in this case, quite frankly defeats the purpose of having a backup.
So I thought of using Google Drive as a safer place to keep the db file, that and it's free. I've taken a peek into Google's quickstart demo which I got working just fine. But I still have no idea how to get this done for my case.
I've found some code to fiddle with but it's still using some deprecated methods and so far I've only managed to run it when omitting the deprecated area but it only creates a blank binary file in my Google Drive so I think that deprecated area is where it actually uploads the DB backup content. If anyone could help out that would be greatly appreciated.
I'll leave it down below in case anyone can use it to explain things to me better. I've also marked the deprecated method below, it's near the end.
public class ExpectoPatronum extends Activity implements ConnectionCallbacks, OnConnectionFailedListener {
private static final String TAG = "MainActivity";
private GoogleApiClient api;
private boolean mResolvingError = false;
private DriveFile mfile;
private static final int DIALOG_ERROR_CODE =100;
private static final String DATABASE_NAME = "demodb";
private static final String GOOGLE_DRIVE_FILE_NAME = "sqlite_db_backup";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create the Drive API instance
api = new GoogleApiClient.Builder(this).addApi(Drive.API).addScope(Drive.SCOPE_FILE).
addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
}
#Override
public void onStart() {
super.onStart();
if(!mResolvingError) {
api.connect(); // Connect the client to Google Drive
}
}
#Override
public void onStop() {
super.onStop();
api.disconnect(); // Disconnect the client from Google Drive
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.v(TAG, "Connection failed");
if(mResolvingError) { // If already in resolution state, just return.
return;
} else if(result.hasResolution()) { // Error can be resolved by starting an intent with user interaction
mResolvingError = true;
try {
result.startResolutionForResult(this, DIALOG_ERROR_CODE);
} catch (SendIntentException e) {
e.printStackTrace();
}
} else { // Error cannot be resolved. Display Error Dialog stating the reason if possible.
ErrorDialogFragment fragment = new ErrorDialogFragment();
Bundle args = new Bundle();
args.putInt("error", result.getErrorCode());
fragment.setArguments(args);
fragment.show(getFragmentManager(), "errordialog");
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == DIALOG_ERROR_CODE) {
mResolvingError = false;
if(resultCode == RESULT_OK) { // Error was resolved, now connect to the client if not done so.
if(!api.isConnecting() && !api.isConnected()) {
api.connect();
}
}
}
}
#Override
public void onConnected(Bundle connectionHint) {
Log.v(TAG, "Connected successfully");
/* Connection to Google Drive established. Now request for Contents instance, which can be used to provide file contents.
The callback is registered for the same. */
Drive.DriveApi.newDriveContents(api).setResultCallback(contentsCallback);
}
final private ResultCallback<DriveApi.DriveContentsResult> contentsCallback = new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.v(TAG, "Error while trying to create new file contents");
return;
}
String mimeType = MimeTypeMap.getSingleton().getExtensionFromMimeType("db");
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle(GOOGLE_DRIVE_FILE_NAME) // Google Drive File name
.setMimeType(mimeType)
.setStarred(true).build();
// create a file on root folder
Drive.DriveApi.getRootFolder(api)
.createFile(api, changeSet, result.getDriveContents())
.setResultCallback(fileCallback);
}
};
final private ResultCallback<DriveFileResult> fileCallback = new ResultCallback<DriveFileResult>() {
#Override
public void onResult(DriveFileResult result) {
if (!result.getStatus().isSuccess()) {
Log.v(TAG, "Error while trying to create the file");
return;
}
mfile = result.getDriveFile();
mfile.open(api, DriveFile.MODE_WRITE_ONLY, null).setResultCallback(contentsOpenedCallback);
}
};
final private ResultCallback<DriveApi.DriveContentsResult> contentsOpenedCallback = new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.v(TAG, "Error opening file");
return;
}
try {
FileInputStream is = new FileInputStream(getDbPath());
BufferedInputStream in = new BufferedInputStream(is);
byte[] buffer = new byte[8 * 1024];
DriveContents content = result.getDriveContents();
BufferedOutputStream out = new BufferedOutputStream(content.getOutputStream());
int n = 0;
while( ( n = in.read(buffer) ) > 0 ) {
out.write(buffer, 0, n);
}
in.close();
commitAndCloseContents is DEPRECATED -->/**mfile.commitAndCloseContents(api, content).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status result) {
// Handle the response status
}
});**/
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
private File getDbPath() {
return this.getDatabasePath(DATABASE_NAME);
}
#Override
public void onConnectionSuspended(int cause) {
// TODO Auto-generated method stub
Log.v(TAG, "Connection suspended");
}
public void onDialogDismissed() {
mResolvingError = false;
}
public static class ErrorDialogFragment extends DialogFragment {
public ErrorDialogFragment() {}
public Dialog onCreateDialog(Bundle savedInstanceState) {
int errorCode = this.getArguments().getInt("error");
return GooglePlayServicesUtil.getErrorDialog(errorCode, this.getActivity(), DIALOG_ERROR_CODE);
}
public void onDismiss(DialogInterface dialog) {
((ExpectoPatronum) getActivity()).onDialogDismissed();
}
}
}
Both APIs used to access Google Drive deal with a binary content. So the only thing you have to do is to upload your binary DB file, give it a proper MIME type and a NAME (title).
The selection of API depends on you, GDAA behaves like a 'local' entity with uploads / downloads handled by Google Play Services, REST Api is more low-level, giving you more control, but you have to take care of networking issues (wifi on/off, etc), i.e. you usually have to build a sync service to do so. With GDAA it is done for you by GooPlaySvcs. But I digress.
I can point you to this GitHub demo, fairly recent (GooPlaySvcs 7.00.+), I use to test different REST / GDAA issues.
The MainActivity is a bit complicated by the fact that it allows for switching between different Google accounts, but if you get through these hurdles, you can use either REST or GDAA CRUD wrappers.
Take look at this line. The byte[] buffer contains binary JPEG data and it goes with "image/jpeg" mime type (and a time-based name). The only thing you have to do if is load your DB file into a byte[] buffer using a construct like this:
private static final int BUF_SZ = 4096;
static byte[] file2Bytes(File file) {
if (file != null) try {
return is2Bytes(new FileInputStream(file));
} catch (Exception ignore) {}
return null;
}
static byte[] is2Bytes(InputStream is) {
byte[] buf = null;
BufferedInputStream bufIS = null;
if (is != null) try {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
bufIS = new BufferedInputStream(is);
buf = new byte[BUF_SZ];
int cnt;
while ((cnt = bufIS.read(buf)) >= 0) {
byteBuffer.write(buf, 0, cnt);
}
buf = byteBuffer.size() > 0 ? byteBuffer.toByteArray() : null;
} catch (Exception e) {le(e);}
finally {
try {
if (bufIS != null) bufIS.close();
} catch (Exception e) {le(e);}
}
return buf;
}
I don't remember the MIME type for SQLite DB now, but I am sure it can be done since I was doing exactly that once (the code is gone now, unfortunately). And I remember I could actually access and modify the SQLite DB 'up in the cloud' using some web app.
Good Luck
UPDATE:
After I wrote the rant above I looked at the demo you're talking about. If you have it working, the easiest way is actually to plug your DB file right here, set the correct MIME and you're good to go. Take you pick.
And to address your 'deprecated' issue. GDAA is still being developed and the quickstart is over a year old. That's the world we live in :-)
You need to replace the deprecated code with:
contents.commit(api, null);
See https://developer.android.com/reference/com/google/android/gms/drive/DriveContents.html

How to display test data received from server in Android

I am writing an app that involves Client -> Server -> Client communication (one way traffic). I have my data transmitted from client A to the server, simple to test, just print to console, however, I'm trying to test to see if the data has been sent on to the next client. I have tried a text view, nothing is displaying in this view however, now I don't know if that's because the data hasn't arrived or indeed because I've coded it wrong. I'm not very experienced in android.
I've attached my code below, if anyone can help I would really appreciate it.
Regards,
Gary
public class Parent extends Activity {
private Socket s;
private PrintWriter p;
String location;
double Platitude, Plongitude;
double Clatitude, Clongitude;
double distance;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.parent);
Thread rec = new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
try {
s = new Socket("192.168.1.2", 1980);
InputStream fromServer = s.getInputStream();
while (s.isConnected()) {
Scanner r = new Scanner(fromServer);
if(r.hasNextLine())
{
location = r.nextLine();
}
TextView myTextview = (TextView) findViewById(R.id.dist);
myTextview.setText(location);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
rec.start();
}

Bind Socket Android

I have a problem on android. I have an application that asks the user for the local Ip address (from the device's interface) and another remote address. The application has to bind to the specified local address and connect to the remote address. Quite simple, but, indeed, bind does not work ass i expected..
I added the following permissions on the manifest file:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
The source code is the following one:
public class MainActivity extends Activity
{
String Tag = "TAG";
private int LOCAL_PORT = 4444;
private int REMOTE_PORT = 80;
private EditText LOCAL;
private EditText REMOTE;
private Button Connect;
private TextView STATUS;
private Context context = this;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LOCAL = (EditText) findViewById(R.id.editText1);
REMOTE = (EditText) findViewById(R.id.editText2);
Connect = (Button) findViewById(R.id.button1);
Connect.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
BotleneckHandle WORK;
Toast.makeText(getApplicationContext(), "Proceeding to connect",
Toast.LENGTH_SHORT).show();
/*
if(LOCAL.getText().toString() == null || REMOTE.getText().toString() == null || LOCAL.getText().toString().equals(" ") || REMOTE.getText().toString().equals(" ") || LOCAL.getText().toString().equals("") || REMOTE.getText().toString().equals(""))
Toast.makeText(context, "Wrong parameters", 2000);
else
{
Toast.makeText(getApplicationContext(), "Proceeding to connect",Toast.LENGTH_SHORT).show();
}*/
WORK = new BotleneckHandle();
WORK.execute();
}
});
STATUS = (TextView) findViewById(R.id.textView1);
}
private class BotleneckHandle extends AsyncTask <Void , Void , String>
{
Socket Skt = null;
String ReturnStatemente = new String();
SocketAddress localAddr = new InetSocketAddress(LOCAL.getText().toString(), LOCAL_PORT);
protected void onPreExecute(){ }
protected String doInBackground(Void... params)
{
try
{
String s=new String();
s+= "Local="+LOCAL.getText().toString()+":"+LOCAL_PORT+" Remote="+REMOTE.getText().toString()+":"+REMOTE_PORT; //so far so good, Confirmed by debug
Toast.makeText(getApplicationContext(), s,Toast.LENGTH_SHORT).show(); //Does not show anything due the fact that i didn't published it as an assync task update..
//binding to a local address
Skt.bind(localAddr); //cannot make the bind :-/
//connecting to remote host
Skt=new Socket(REMOTE.getText().toString(), REMOTE_PORT); //if bind is comment, still does not work.. I bet
ReturnStatemente = "Connected";
}
catch (UnknownHostException e)
{
e.printStackTrace();
Toast.makeText(context, "Unknown remote host", 2000);
ReturnStatemente = "Not Connected";
}
catch (IOException e)
{
e.printStackTrace();
Toast.makeText(context, "Connection fail", 2000);
ReturnStatemente = "Not Connected";
}
finally{try {
Skt.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
return ReturnStatemente;
}
protected void onPostExecute(String result) { STATUS.setText(" CONECTION STATUS == " + result); }
}
}
What am i doing wrong on bind? As far as i see, and as i searched for its good.. Did i miss something?
kind regards
You're trying to call bind on a variable before you assigned anything to it. So its still null. That isn't going to work. You need to create an instance of Socket before you can call methods on it.

Can't start an activity in application onCreate

I am trying to start an activity after n seconds with a handler. The application was crashing on the startActivity call, so I put the handler code in my application's onCreate, and it is still crashing (which makes me think that the error comes from me not using startActivity well) :
#Override
public void onCreate(){
String roomName = this.getSettingValue(R.string.PREFERENCES_ROOM_NAME, "");
Room room;
try {
room = this.getRoomWithName(roomName);
} catch (ReservatorException ex) {
Toast err = Toast.makeText(this, ex.getMessage(),
Toast.LENGTH_LONG);
err.show();
return;
}
Intent i = new Intent(this, RoomActivity.class);
i.putExtra("room", room);
this.startActivity(i);
}
Strange thing is that this work when called from a view, by using exactly the same code, but different context :
Intent i = new Intent(getContext(), RoomActivity.class);
// ...
I am pretty new to Android ... so there may be information missing in that question, or I might even be trying to do something completely stupid who knows ?
EDIT
Link to the stacktrace : http://pastebin.com/vh2QC3xz
EDIT2
Here is the handler version of my code (so what I am trying to do in the end) :
public class ReservatorApplication extends Application {
private GoToFavouriteRoom goToFavouriteRoomRunable;
class GoToFavouriteRoom implements Runnable {
ReservatorApplication app;
public GoToFavouriteRoom(ReservatorApplication anApp){
app = anApp;
}
#Override
public void run() {
String roomName = app.getSettingValue(R.string.PREFERENCES_ROOM_NAME, "");
Room room;
try {
room = app.getDataProxy().getRoomWithName(roomName);
} catch (ReservatorException ex) {
Toast err = Toast.makeText(app, ex.getMessage(),
Toast.LENGTH_LONG);
err.show();
return;
}
RoomActivity.startWith(app, room);
}
}
private final ReservatorAppHandler handler = new ReservatorAppHandler();
class ReservatorAppHandler extends Handler{
#Override
public void handleMessage(Message msg){
return;
}
}
#Override
public void onCreate(){
String serverAddress = getSettingValue(R.string.PREFERENCES_SERVER_ADDRESS, "mail.futurice.com");// TODO: change to mail.futurice.com before delivery
proxy = new SoapDataProxy(serverAddress);
// proxy = new DummyDataProxy();
proxy = new CachedDataProxy(proxy);
addressBook = new FumAddressBook();
try {
addressBook.prefetchEntries();
} catch (ReservatorException e) {
// TODO: DIE!
}
goToFavouriteRoomRunable = new GoToFavouriteRoom(this);
handler.postDelayed(goToFavouriteRoomRunable, 20000);
}
Ok ... I finally solved my problem, mainly thanks to #Drax
Apparently, you just can't start an activity from an application ... you need an instance of an activity. So :
public class ReservatorApplication extends Application {
#Override
public void onCreate(){
Intent i = new Intent(this, RoomActivity.class);
this.startActivity(i);
}
}
Is just not valid, and causes a RunTimeException ...
As far as crashing is concern when you start activity in handler with "this". it will take handler's context. and when you do getContext() it will take activity context.
Intent i = new Intent(YourActivityName.this, RoomActivity.class);
or
Intent i = new Intent(getBaseContext(), RoomActivity.class);
It`s hard to answer without seeing the stack trace from logcat, but I found that sometimes you need to pass the application context to the a new Intent before starting an Activity.
Try this line:
Intent i = new Intent(getApplicationContext(), RoomActivity.class);

Categories

Resources