I am trying to insert data into into MongoDB from my Android application. For this I have written this code (given below) but this code does nothing when I execute insert task. Neither this code gives any error or exception nor it inserts data to the database. So what is the problem and how can I solve this problem?
In SetNotification.java I do this:
Task save_task = new Task();
save_task.date = showDate.getText().toString();
save_task.location = showLocation.getText().toString();
save_task.description = note.getText().toString();
SaveAsyncTask tsk = new SaveAsyncTask(SetNotification.this);
tsk.execute(save_task);
This is SaveAsyncTask.java class:
package com.example.abc.project1.MongoHQ;
/**
* Created by abc on 02-May-16.
*/
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import com.example.abc.project1.SetNotification;
import com.example.abc.project1.Task;
public class SaveAsyncTask extends AsyncTask<Task, Void, Boolean> {
private static Context context;
public SaveAsyncTask(Context c) {
context = c;
}
#Override
protected Boolean doInBackground(Task... arg0) {
try
{
Task task = arg0[0];
QueryBuilder qb = new QueryBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost(qb.buildContactsSaveURL());
StringEntity params =new StringEntity(qb.createTask(task));
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
if(response.getStatusLine().getStatusCode()<205)
{
Toast.makeText(context, "SAVED", Toast.LENGTH_SHORT).show();
return true;
}
else
{
Toast.makeText(context, "Saving failed", Toast.LENGTH_SHORT).show();
return false;
}
} catch (Exception e) {
//Log.e("MYAPP", "exception",e);
e.printStackTrace();
return false;
}
}
}
This QueryBuilder.java class:
package com.example.abc.project1.MongoHQ;
import com.example.abc.project1.Task;
/**
* Created by abc on 02-May-16.
*/
public class QueryBuilder {
/**
* Specify your database name here
* #return
*/
public String getDatabaseName() {
return "location_notification";
}
/**
* Specify your MongoLab API here
* #return
*/
public String getApiKey() {
return "################################";
}
/**
* This constructs the URL that allows you to manage your database,
* collections and documents
* #return
*/
public String getBaseUrl()
{
return "https://api.mongolab.com/api/1/databases/"+getDatabaseName()+"/collections/";
}
/**
* Completes the formating of your URL and adds your API key at the end
* #return
*/
public String docApiKeyUrl()
{
return "?apiKey="+getApiKey();
}
/**
* Returns the docs101 collection
* #return
*/
public String documentRequest()
{
return "tasks";
}
/**
* Builds a complete URL using the methods specified above
* #return
*/
public String buildContactsSaveURL()
{
return getBaseUrl()+documentRequest()+docApiKeyUrl();
}
/**
* Formats the contact details for MongoHQ Posting
* #param : Details of the person
* #return
*/
public String createTask(Task task)
{
return String
.format("{\"document\" : {\"date\": \"%s\", "
+ "\"location\": \"%s\", \"description\": \"%s\"}, \"safe\" : true}",
task.date, task.location, task.description);
}
}
Related
I am trying to push data into AWS DynamoDB but I keep facing this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper com.uploadtodatabasevts.amazonaws.AWSMobileClient.getDynamoDBMapper()' on a null object reference
Any idea on what is missing out or what did I enter wrongly? I can't seem to find out.
Below is the MainActivity class:
For the outfitID its suppose to be a primary key auto increment but i have no idea how to do it on AWS DynamoDB NoSQL so I am currently pushing the ID in manually.
package com.uploadtodatabasevts;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.amazonaws.AmazonClientException;
import com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper;
import com.uploadtodatabasevts.amazonaws.AWSMobileClient;
import com.uploadtodatabasevts.amazonaws.DynamoDBUtils;
import com.uploadtodatabasevts.amazonaws.OutfitDO;
import com.uploadtodatabasevts.amazonaws.ThreadUtils;
public class MainActivity extends AppCompatActivity {
private static final String LOG_TAG = MainActivity.class.getName();
String pID, pDetails;
double oID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText outfitID = (EditText)findViewById(R.id.eTxtOutfitID);
EditText productID = (EditText)findViewById(R.id.eTxtProductID);
pID = productID.getText().toString();
EditText productDetails = (EditText)findViewById(R.id.eTxtProductDetails);
pDetails = productDetails.getText().toString();
Button confirm = (Button)findViewById(R.id.btnConfirm);
confirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
insertData();
}
});
}
private void insertData() throws AmazonClientException {
final DynamoDBMapper dynamoDBMapper = AWSMobileClient.defaultMobileClient().getDynamoDBMapper();
final OutfitDO outfitDO = new OutfitDO();
outfitDO.setOutfitId((double) 10);
outfitDO.setOutfitId(oID);
outfitDO.setItemOneId(pID);
outfitDO.setItemOneDetails(pDetails);
AmazonClientException lastException = null;
try {
dynamoDBMapper.save(outfitDO);
} catch (final AmazonClientException ex) {
Log.e(LOG_TAG, "Failed saving item : " + ex.getMessage(), ex);
lastException = ex;
}
if (lastException != null){
throw lastException;
}
}
}
Below is the AWSMobileClient:
package com.uploadtodatabasevts.amazonaws;
import android.content.Context;
import android.util.Log;
import com.amazonaws.ClientConfiguration;
import com.uploadtodatabasevts.amazonaws.IdentityManager;
import com.amazonaws.mobileconnectors.dynamodbv2.dynamodbmapper.DynamoDBMapper;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClient;
/**
* The AWS Mobile Client bootstraps the application to make calls to AWS
* services. It creates clients which can be used to call services backing the
* features you selected in your project.
*/
public class AWSMobileClient {
private static final String LOG_TAG = AWSMobileClient.class.getSimpleName();
private static AWSMobileClient instance;
private final Context context;
private ClientConfiguration clientConfiguration;
private IdentityManager identityManager;
private AmazonDynamoDBClient dynamoDBClient;
private DynamoDBMapper dynamoDBMapper;
/**
* Build class used to create the AWS mobile client.
*/
public static class Builder {
private Context applicationContext;
private String cognitoIdentityPoolID;
private Regions cognitoRegion;
private ClientConfiguration clientConfiguration;
private IdentityManager identityManager;
/**
* Constructor.
* #param context Android context.
*/
public Builder(final Context context) {
this.applicationContext = context.getApplicationContext();
};
/**
* Provides the Amazon Cognito Identity Pool ID.
* #param cognitoIdentityPoolID identity pool ID
* #return builder
*/
public Builder withCognitoIdentityPoolID(final String cognitoIdentityPoolID) {
this.cognitoIdentityPoolID = cognitoIdentityPoolID;
return this;
};
/**
* Provides the Amazon Cognito service region.
* #param cognitoRegion service region
* #return builder
*/
public Builder withCognitoRegion(final Regions cognitoRegion) {
this.cognitoRegion = cognitoRegion;
return this;
}
/**
* Provides the identity manager.
* #param identityManager identity manager
* #return builder
*/
public Builder withIdentityManager(final IdentityManager identityManager) {
this.identityManager = identityManager;
return this;
}
/**
* Provides the client configuration
* #param clientConfiguration client configuration
* #return builder
*/
public Builder withClientConfiguration(final ClientConfiguration clientConfiguration) {
this.clientConfiguration = clientConfiguration;
return this;
}
/**
* Creates the AWS mobile client instance and initializes it.
* #return AWS mobile client
*/
public AWSMobileClient build() {
return
new AWSMobileClient(applicationContext,
cognitoIdentityPoolID,
cognitoRegion,
identityManager,
clientConfiguration);
}
}
private AWSMobileClient(final Context context,
final String cognitoIdentityPoolID,
final Regions cognitoRegion,
final IdentityManager identityManager,
final ClientConfiguration clientConfiguration) {
this.context = context;
this.identityManager = identityManager;
this.clientConfiguration = clientConfiguration;
this.dynamoDBClient = new AmazonDynamoDBClient(identityManager.getCredentialsProvider(), clientConfiguration);
this.dynamoDBClient.setRegion(Region.getRegion(AWSConfiguration.AMAZON_DYNAMODB_REGION));
this.dynamoDBMapper = new DynamoDBMapper(dynamoDBClient);
}
/**
* Sets the singleton instance of the AWS mobile client.
* #param client client instance
*/
public static void setDefaultMobileClient(AWSMobileClient client) {
instance = client;
}
/**
* Gets the default singleton instance of the AWS mobile client.
* #return client
*/
public static AWSMobileClient defaultMobileClient() {
return instance;
}
/**
* Gets the identity manager.
* #return identity manager
*/
public IdentityManager getIdentityManager() {
return this.identityManager;
}
/**
* Creates and initialize the default AWSMobileClient if it doesn't already
* exist using configuration constants from {#link AWSConfiguration}.
*
* #param context an application context.
*/
public static void initializeMobileClientIfNecessary(final Context context) {
if (AWSMobileClient.defaultMobileClient() == null) {
Log.d(LOG_TAG, "Initializing AWS Mobile Client...");
final ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setUserAgent(AWSConfiguration.AWS_MOBILEHUB_USER_AGENT);
final IdentityManager identityManager = new IdentityManager(context, clientConfiguration);
final AWSMobileClient awsClient =
new AWSMobileClient.Builder(context)
.withCognitoRegion(AWSConfiguration.AMAZON_COGNITO_REGION)
.withCognitoIdentityPoolID(AWSConfiguration.AMAZON_COGNITO_IDENTITY_POOL_ID)
.withIdentityManager(identityManager)
.withClientConfiguration(clientConfiguration)
.build();
AWSMobileClient.setDefaultMobileClient(awsClient);
}
Log.d(LOG_TAG, "AWS Mobile Client is OK");
}
/**
* Gets the DynamoDB Client, which allows accessing Amazon DynamoDB tables.
* #return the DynamoDB client instance.
*/
public AmazonDynamoDBClient getDynamoDBClient() {
return dynamoDBClient;
}
/**
* Gets the Dynamo DB Object Mapper, which allows accessing DynamoDB tables using annotated
* data object classes to represent your data using POJOs (Plain Old Java Objects).
* #return the DynamoDB Object Mapper instance.
*/
public DynamoDBMapper getDynamoDBMapper() {
return dynamoDBMapper;
}
}
Your Application class should have code that initializes the mobile client by calling AWSMobileClient.initializeMobileClientIfNecessary(context) otherwise AWSMobileClient.defaultMobileClient() will return null. If you do not have a custom Application class, you could call AWSMobileClient.initializeMobileClientIfNecessary(context) in your Activity's onCreate() lifecycle method.
I am trying to insert data into MongoDB from my Android application. For this I have written this code (given below) but this code pops-up an error when I click save button (for inserting data into MongoDB).
Error: Unfortunately, Project1 has stopped.
So what is the problem in this code and how can I solve that problem?
Code behind insert/save button:
Task save_task = new Task();
save_task.date = showDate.getText().toString();
save_task.location = showLocation.getText().toString();
save_task.description = note.getText().toString();
SaveAsyncTask tsk = new SaveAsyncTask(SetNotification.this);
tsk.execute(save_task);
Task.java Class:
package com.example.abc.project1;
/**
* Created by abc on 02-May-16.
*/
public class Task {
public String date;
public String location;
public String description;
}
SaveAsyncTask.java Class:
package com.example.abc.project1.MongoHQ;
/**
* Created by abc on 02-May-16.
*/
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import com.example.abc.project1.SetNotification;
import com.example.abc.project1.Task;
public class SaveAsyncTask extends AsyncTask<Task, Void, Boolean> {
private static Context context;
public SaveAsyncTask(Context c) {
context = c;
}
#Override
protected Boolean doInBackground(Task... arg0) {
try {
Task task = arg0[0];
QueryBuilder qb = new QueryBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpPost request = new HttpPost(qb.buildContactsSaveURL());
StringEntity params =new StringEntity(qb.createTask(task));
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
if(response.getStatusLine().getStatusCode()<205)
{
return true;
}
else
{
return false;
}
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
QueryBuilder.java Class:
package com.example.abc.project1.MongoHQ;
import com.example.abc.project1.Task;
/**
* Created by abc on 02-May-16.
*/
public class QueryBuilder {
/**
* Specify your database name here
* #return
*/
public String getDatabaseName() {
return "location_notification";
}
/**
* Specify your MongoLab API here
* #return
*/
public String getApiKey() {
return "#########";
}
/**
* This constructs the URL that allows you to manage your database,
* collections and documents
* #return
*/
public String getBaseUrl()
{
return "https://api.mongolab.com/api/1/databases/"+getDatabaseName()+"/collections/";
}
/**
* Completes the formating of your URL and adds your API key at the end
* #return
*/
public String docApiKeyUrl()
{
return "?apiKey="+getApiKey();
}
/**
* Returns the tasks collection
* #return
*/
public String documentRequest()
{
return "tasks";
}
/**
* Builds a complete URL using the methods specified above
* #return
*/
public String buildContactsSaveURL()
{
return getBaseUrl()+documentRequest()+docApiKeyUrl();
}
/**
* Formats the contact details for MongoHQ Posting
* #param : Details of the Task
* #return
*/
public String createTask(Task task)
{
return String
.format("{\"document\" : {\"date\": \"%s\", "
+ "\"location\": \"%s\", \"description\": \"%s\"}, \"safe\" : true}",
task.date, task.location, task.description);
}
}
I have an array of Urls which I would synchronously.
In fact I'm in an asynctask with a for loop.
I tried using downloadmanager and broadcast receiver without success (the manager use another thread so I can't unregister each time, a leak append).
This is my Asynctask :
package com.ylly.hypred.splashScreen.asynctask;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;
import android.view.WindowManager;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.ylly.hypred.R;
import com.ylly.hypred.api.CallAPI;
import com.ylly.hypred.api.model.MediaAPIModel;
import com.ylly.hypred.api.model.MediaArrayAPIModel;
import com.ylly.hypred.utils.FileManager;
import java.io.File;
import java.util.ArrayList;
/**
* Created by YLLY on 17-11-2015.
*/
public class LoadMedias extends AsyncTask<String, Void, String> {
private MediaArrayAPIModel mediaAPIModels;
private Context context;
private ProgressDialog progressDialog;
private boolean isCallFromUpdate;
private final String TAG = "LoadMedias";
private OnLoadingIsFinished mCallback;
/**
*
*/
public interface OnLoadingIsFinished {
void callProcess();
}
/**
*
* #param context
* #param urls
* #param isCallFromUpdate
*/
public LoadMedias(Context context, MediaArrayAPIModel urls, boolean isCallFromUpdate) {
this.context = context;
this.mediaAPIModels = urls;
progressDialog = new ProgressDialog(context);
this.isCallFromUpdate = isCallFromUpdate;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (!isCallFromUpdate)
progressDialog.setTitle(context.getString(R.string.fm_etape_trois_sur_trois));
progressDialog.setMessage(context.getString(R.string.fm_enregistrement));
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
progressDialog.setMax(mediaAPIModels.getMediaImagePIModels().size() + mediaAPIModels.getMediaFileAPIModels().size());
progressDialog.setProgress(0);
progressDialog.show();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
mCallback.callProcess();
}
#Override
protected String doInBackground(String... arg0) {
try {
loadMediaImages(mediaAPIModels.getMediaImagePIModels(), progressDialog);
loadMediaFiles(context, mediaAPIModels.getMediaFileAPIModels(), progressDialog);
} catch (Exception e) {
Log.d(TAG, e.toString());
}
return "";
}
/**
*
* #param onLoadingIsFinished
*/
public void setOnLoadingIsFinished(OnLoadingIsFinished onLoadingIsFinished) {
this.mCallback = onLoadingIsFinished;
}
/**
* #param mediaAPIModels
* #param progressDialog
*/
private void loadMediaImages(ArrayList<MediaAPIModel> mediaAPIModels, ProgressDialog progressDialog) {
String type;
for (int i = 0; i < mediaAPIModels.size(); i++) {
type = mediaAPIModels.get(i).getUrl().substring(mediaAPIModels.get(i).getUrl().lastIndexOf("."));
if (type.equals(".png") || type.equals(".jpg") || type.equals(".jpeg")) {
ImageLoader.getInstance().loadImageSync(CallAPI.mBaseUrl + mediaAPIModels.get(i).getUrl());
i++;
progressDialog.setProgress(progressDialog.getProgress() + 1);
}
}
}
/**
* #param context
* #param mediaAPIModels
* #param progressDialog
*/
private void loadMediaFiles(Context context, ArrayList<MediaAPIModel> mediaAPIModels, final ProgressDialog progressDialog) {
{
String name;
String mime;
for (int i = 0; i < mediaAPIModels.size(); i++) {
if (!FileManager.getInstance().getFileFromLocal(context, mediaAPIModels.get(i).getUrl(), false)) {
name = mediaAPIModels.get(i).getUrl().substring(mediaAPIModels.get(i).getUrl().lastIndexOf("/") + 1); //on sépare le nom du fichier du reste de l'url
mime = name.substring(name.lastIndexOf(".")); //on recupere l'extension du fichier
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(CallAPI.mBaseUrl + mediaAPIModels.get(i).getUrl()));
request.setDescription(context.getResources().getString(R.string.downloading) + " name");
request.setTitle(context.getResources().getString(R.string.app_name));
request.setMimeType(mime);
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir("test" + File.separatorChar + "doc", name);
// get download service and enqueue file
DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
context.registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
context.unregisterReceiver(this);
Log.d("DOWNLOAD", "unregister");
progressDialog.setProgress(progressDialog.getProgress() + 1);
}
}, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
} else {
i++;
progressDialog.setProgress(progressDialog.getProgress() + 1);
}
}
}
}
}
The cache loading works.
Thanks in advance ;)
I have this EndPointAsyncTask.class into my app module:
package com.kkoci.shairlook;
/**
* Created by kristian on 02/07/2015.
*/
import android.content.Context;
import android.os.AsyncTask;
import android.util.Pair;
import android.widget.Toast;
import com.appspot.shairlook1.userEndpoint.UserEndpoint;
import com.appspot.shairlook1.userEndpoint.model.User;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.extensions.android.json.AndroidJsonFactory;
import com.google.api.client.googleapis.services.AbstractGoogleClientRequest;
import com.google.api.client.googleapis.services.GoogleClientRequestInitializer;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
class EndpointsAsyncTask extends AsyncTask<Void, Void, List<User>> {
private static UserEndpoint myApiService = null;
private Context context;
EndpointsAsyncTask(Context context) {
this.context = context;
}
#Override
protected List<User> doInBackground(Void... params) {
if(myApiService == null) { // Only do this once
UserEndpoint.Builder builder = new UserEndpoint().Builder(AndroidHttp.newCompatibleTransport(),
new AndroidJsonFactory(), null)
// options for running against local devappserver
// - 10.0.2.2 is localhost's IP address in Android emulator
// - turn off compression when running against local devappserver
.setRootUrl("http://10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
#Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});
// end options for devappserver
myApiService = builder.build();
}
try {
return myApiService.listUser().execute().getItems();
} catch (IOException e) {
return Collections.EMPTY_LIST;
}
}
#Override
protected void onPostExecute(List<User> result) {
for (User q : result) {
Toast.makeText(context, q.getWho() + " : " + q.getWhat(), Toast.LENGTH_LONG).show();
}
}
}
This consumes from User class into my backend module from google app engine:
package com.kkoci.shairlook.backend;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
/**
* Created by kristian on 01/07/2015.
*/
#Entity
public class User {
#Id
Long id;
String who;
String what;
public User() {}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getWho() {
return who;
}
public void setWho(String who) {
this.who = who;
}
public String getWhat() {
return what;
}
public void setWhat(String what) {
this.what = what;
}
}
This is my UserEndPoint class:
package com.kkoci.shairlook.backend;
import com.kkoci.shairlook.backend.User;
import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.api.server.spi.config.ApiNamespace;
import com.google.api.server.spi.config.Nullable;
import com.google.api.server.spi.response.CollectionResponse;
import com.google.api.server.spi.response.ConflictException;
import com.google.api.server.spi.response.NotFoundException;
import com.google.appengine.api.datastore.Cursor;
import com.google.appengine.api.datastore.QueryResultIterator;
import com.googlecode.objectify.cmd.Query;
import static com.kkoci.shairlook.backend.OfyService.ofy;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import javax.inject.Named;
/**
* Created by kristian on 01/07/2015.
*/
#Api(name = "userEndpoint", version = "v1", namespace = #ApiNamespace(ownerDomain = "shairlook1.appspot.com", ownerName = "shairlook1.appspot.com", packagePath=""))
public class UserEndPoint {
// Make sure to add this endpoint to your web.xml file if this is a web application.
public UserEndPoint() {
}
/**
* Return a collection of users
*
* #param count The number of users
* #return a list of Users
*/
#ApiMethod(name = "listUser")
public CollectionResponse<User> listUser(#Nullable #Named("cursor") String cursorString,
#Nullable #Named("count") Integer count) {
Query<User> query = ofy().load().type(User.class);
if (count != null) query.limit(count);
if (cursorString != null && cursorString != "") {
query = query.startAt(Cursor.fromWebSafeString(cursorString));
}
List<User> records = new ArrayList<User>();
QueryResultIterator<User> iterator = query.iterator();
int num = 0;
while (iterator.hasNext()) {
records.add(iterator.next());
if (count != null) {
num++;
if (num == count) break;
}
}
//Find the next cursor
if (cursorString != null && cursorString != "") {
Cursor cursor = iterator.getCursor();
if (cursor != null) {
cursorString = cursor.toWebSafeString();
}
}
return CollectionResponse.<User>builder().setItems(records).setNextPageToken(cursorString).build();
}
/**
* This inserts a new <code>User</code> object.
* #param user The object to be added.
* #return The object to be added.
*/
#ApiMethod(name = "insertUser")
public User insertUser(User user) throws ConflictException {
//If if is not null, then check if it exists. If yes, throw an Exception
//that it is already present
if (user.getId() != null) {
if (findRecord(user.getId()) != null) {
throw new ConflictException("Object already exists");
}
}
//Since our #Id field is a Long, Objectify will generate a unique value for us
//when we use put
ofy().save().entity(user).now();
return user;
}
/**
* This updates an existing <code>User</code> object.
* #param user The object to be added.
* #return The object to be updated.
*/
#ApiMethod(name = "updateUser")
public User updateUser(User user)throws NotFoundException {
if (findRecord(user.getId()) == null) {
throw new NotFoundException("User Record does not exist");
}
ofy().save().entity(user).now();
return user;
}
/**
* This deletes an existing <code>User</code> object.
* #param id The id of the object to be deleted.
*/
#ApiMethod(name = "removeUser")
public void removeUser(#Named("id") Long id) throws NotFoundException {
User record = findRecord(id);
if(record == null) {
throw new NotFoundException("User Record does not exist");
}
ofy().delete().entity(record).now();
}
//Private method to retrieve a <code>User</code> record
private User findRecord(Long id) {
return ofy().load().type(User.class).id(id).now();
//or return ofy().load().type(User.class).filter("id",id).first.now();
}
}
I'm using GAE version 1.9.18...
I don't know if this a version issue, but on EndpointAsyncTask into this line:
UserEndpoint.Builder builder = new UserEndpoint().Builder(AndroidHttp.newCompatibleTransport(),
The EndpointAsyncTask keep throwing this error:
Error:(33, 44) error: no suitable constructor found for UserEndpoint()
constructor UserEndpoint.UserEndpoint(Builder) is not applicable
(actual and formal argument lists differ in length)
constructor UserEndpoint.UserEndpoint(HttpTransport,JsonFactory,HttpRequestInitializer) is not applicable
(actual and formal argument lists differ in length)
I don't know what it could be, this is my backend GAE gradle conf:
dependencies {
appengineSdk 'com.google.appengine:appengine-java-sdk:1.9.18'
compile 'com.google.appengine:appengine-endpoints:1.9.18'
compile 'com.google.appengine:appengine-endpoints-deps:1.9.18'
compile 'com.googlecode.objectify:objectify:5.0.3'
compile 'javax.servlet:servlet-api:2.5'
}
Any ideas?
Thanks in advance!
Your Builder constructor.
You are creating a new Builder instance as
UserEndpoint.Builder builder = new UserEndpoint().Builder(AndroidHttp.newCompatibleTransport()...)
but needs to be called as
UserEndpoint.Builder builder = new UserEndpoint.Builder(AndroidHttp.newCompatibleTransport()...)
I'm having some kind of logical problem with my code for saving on internal storage.
I created two methods in the class pet for load and save where I'm trying to save and load an instance of pet. I don't get any error messages in logcat, but nothing is saved when I quit and then open the application again.
package Model;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import edu.chl.dat255.sofiase.readyforapet.CreatePet;
import android.content.Context;
public class Pet implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
PetMood petMood = new PetMood();
private int hungerCounter;
private int walkCounter;
private int playCounter;
/**
* Method that increases mood bar while eating
*
* #return String with the pet's reaction
*/
public String eat() {
//walkCounter = petMood.getWalkMood();
hungerCounter = petMood.getFoodMood();
//playCounter = petMood.getPlayMood();
if (hungerCounter < 5) {
hungerCounter = hungerCounter + 1;
petMood.setFoodMood(hungerCounter);
return "Yummie!";
}
else{
return "I am full";
}
}
/**
* Method that increases mood bar while walking
* and decides that the dog can't walk when it is too hungry or too tired
*
* #return String with the pet's reaction
*/
public String walk() {
walkCounter = petMood.getWalkMood();
hungerCounter = petMood.getFoodMood();
playCounter = petMood.getPlayMood();
if (hungerCounter < 3 && walkCounter < 5)
return "I'm too hungry!";
else if (playCounter + walkCounter > 6)
return "I'm tired! I want to rest!";
else if (walkCounter < 5) {
walkCounter = walkCounter + 1;
petMood.setWalkMood(walkCounter);
return "Yeey! Great exercise!";
}
else{
return "I'm tired! I want to rest!";
}
}
/**
* Method that increases mood bar while playing
* and decides that the dog can't play when it is too hungry or too tired
*
* #return String with the pet's reaction
*/
public String play() {
walkCounter = petMood.getWalkMood();
hungerCounter = petMood.getFoodMood();
playCounter = petMood.getPlayMood();
if (playCounter + walkCounter > 6) {
return "I'm tired! I want to rest!";
}
else if (hungerCounter <3 && playCounter < 5)
return "I'm too hungry!";
else if (playCounter < 5 ) {
playCounter = playCounter + 1;
petMood.setPlayMood(playCounter);
return "Yeey! Lots of fun!";
}
else{
return "I'm tired! I want to rest!";
}
}
public void save(String FILENAME, Context context) throws FileNotFoundException, IOException{
FileOutputStream fos = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);
ObjectOutputStream savedPet = new ObjectOutputStream(fos);
savedPet.writeObject(context.getApplicationContext());
savedPet.close();
}
public static Pet load(String FILENAME, Context context) throws FileNotFoundException, IOException, ClassNotFoundException{
FileInputStream fis = context.openFileInput(FILENAME);
ObjectInputStream ois = new ObjectInputStream(fis);
Pet pet = (Pet) ois.readObject();
ois.close();
CreatePet.setPet(pet);
return pet;
}
}
package edu.chl.dat255.sofiase.readyforapet;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import Model.Dog;
import Model.Pet;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class CreatePet extends Activity implements OnClickListener, Serializable { //lagt till interface serializivble. kanske inte n�dv�ndigt
/**
*
*/
private static final long serialVersionUID = 1L;
String petName;
private static Dog dog;
String FILENAME = "pet_file.dat";//lagts till f�r nullpointerexeption
/**
* onCreate Method
*
*
* #param savedInstanceState - Bundle
*/
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView(R.layout.createpet);
Button create = (Button) findViewById(R.id.puppy_settings);
create.setOnClickListener(this);
}
public void onClick (View v){
startActivity(new Intent(CreatePet.this, PetActivity.class));
EditText setName = (EditText) findViewById(R.id.edit_pet_name);
petName = setName.getText().toString();
dog = new Dog(petName);
try {
dog.save("pet_file.dat", this);
} catch (FileNotFoundException e) {
System.out.print("File not found kastad i CreatePet");
e.printStackTrace();
} catch (IOException e) {
System.out.print("IOException kastad i CreatePet");
e.printStackTrace();
}
}
/**
* getPet Method
*
* makes the created pet available to other classes
*
* #return dog - an instance of the class Dog
*/
public static Pet getPet(){
return dog;
}
/**
* getPet Method
*
* makes the created pet available to other classes
*
* #return dog - an instance of the class Dog
*/
public static void setPet(Pet pet){
dog = (Dog) pet;
}
}
package edu.chl.dat255.sofiase.readyforapet;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import Model.Pet;
import Model.Dog;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class SelectGame extends Activity implements Serializable {// la till f�r att objektet m�ste vara serializible
private static final long serialVersionUID = 1L;
TextView failMessage;
String FILENAME = "pet_file.dat";// lgts till f�r nullpointerexep
/**
* onCreate method
*
* #param savedInstanceState - Bundle
*/
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView(R.layout.selectgame);
//The continue button reacts to a click and starts PetActivity
Button continuePreviousGame = (Button) findViewById(R.id.continuegame);
continuePreviousGame.setOnClickListener(new OnClickListener() {
/**
* Method onClick for the continue previous game button
*
* #param v - View
*/
public void onClick (View v){
try {
Pet.load("pet_file.dat",SelectGame.this);
} catch (FileNotFoundException e) {
System.out.print("File not found ");
e.printStackTrace();
} catch (IOException e) {
System.out.print("IO Exception ");
e.printStackTrace();
} catch (ClassNotFoundException e) {
System.out.print("Class not found exception ");
e.printStackTrace();
}
if (CreatePet.getPet() != null){
startActivity(new Intent(SelectGame.this, PetActivity.class));
}
else{
failMessage = (TextView) findViewById(R.id.failmessage);
failMessage.setText("Create a pet first!");
}
}
}
);
//To send the button CreateNewPet to the activity CreatePet
Button createNewPet = (Button) findViewById(R.id.createnewpet);
createNewPet.setOnClickListener(new OnClickListener() {
/**
* Method onClick for the create new pet button
*
* #param v - View
*/
public void onClick (View v){
startActivity(new Intent(SelectGame.this, CreatePet.class));
}
}
);
}
}
You are saving the wrong object. Your code saves a Context and tries to reload it as a Pet.
Instead of
savedPet.writeObject(context.getApplicationContext());
you should be doing
savedPet.writeObject(this);