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 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);
}
}
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()...)
Am trying to integrate twitter with my application to share message and image on my twitter wall. But displaying following exception:
05-17 01:06:28.151: D/Twitter Update Error(22720): 401:Authentication credentials (https://dev.twitter.com/pages/auth) were missing or incorrect. Ensure that you have set valid consumer key/secret, access token/secret, and the system clock is in sync.
05-17 01:06:28.151: D/Twitter Update Error(22720): {"request":"\/1.1\/statuses\/update.json","error":"Read-only application cannot POST."}
05-17 01:06:28.161: W/System.err(22720): 401:Authentication credentials (https://dev.twitter.com/pages/auth) were missing or incorrect. Ensure that you have set valid consumer key/secret, access token/secret, and the system clock is in sync.
05-17 01:06:28.161: W/System.err(22720): {"request":"\/1.1\/statuses\/update.json","error":"Read-only application cannot POST."}
05-17 01:06:28.161: W/System.err(22720): Relevant discussions can be found on the Internet at:
05-17 01:06:28.161: W/System.err(22720): http://www.google.co.jp/search?q=2fc5b7cb or
05-17 01:06:28.161: W/System.err(22720): http://www.google.co.jp/search?q=11613e08
05-17 01:06:28.161: W/System.err(22720): TwitterException{exceptionCode=[2fc5b7cb-11613e08], statusCode=401, message=null, code=-1, retryAfter=-1, rateLimitStatus=null, version=4.0.1}
05-17 01:06:28.161: W/System.err(22720): at twitter4j.HttpClientImpl.handleRequest(HttpClientImpl.java:164)
05-17 01:06:28.161: W/System.err(22720): at twitter4j.HttpClientBase.request(HttpClientBase.java:53)
05-17 01:06:28.161: W/System.err(22720): at twitter4j.HttpClientBase.post(HttpClientBase.java:82)
05-17 01:06:28.166: W/System.err(22720): at twitter4j.TwitterImpl.post(TwitterImpl.java:2004)
05-17 01:06:28.166: W/System.err(22720): at twitter4j.TwitterImpl.updateStatus(TwitterImpl.java:251)
05-17 01:06:28.166: W/System.err(22720): at com.android.twitterapi.Item$updateTwitterStatus.doInBackground(Item.java:64)
05-17 01:06:28.171: W/System.err(22720): at com.android.twitterapi.Item$updateTwitterStatus.doInBackground(Item.java:1)
05-17 01:06:28.171: W/System.err(22720): at android.os.AsyncTask$2.call(AsyncTask.java:288)
05-17 01:06:28.171: W/System.err(22720): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
05-17 01:06:28.176: W/System.err(22720): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
05-17 01:06:28.176: W/System.err(22720): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
05-17 01:06:28.176: W/System.err(22720): at java.lang.Thread.run(Thread.java:841)
Can anyone please help me?
Following is my code:
MainActivity:
package com.android.twitterapi;
import me.grantland.twitter.Twitter;
import me.grantland.twitter.Twitter.DialogListener;
import me.grantland.twitter.TwitterError;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
public static final String CONSUMER_KEY = "fZRZJcNrFbg55dmr4rLVA";
public static final String CONSUMER_SECRET = "Xbxmn2hlT91mzydcmbnGRqOIYg8Ohipd9F8HfQYhHg";
private Twitter mTwitter;
private Button mTwitterButton;
String access_token ;
// Access Token Secret
String access_token_secret ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
mTwitter = new Twitter(CONSUMER_KEY, CONSUMER_SECRET);
mTwitterButton = (Button)findViewById(R.id.twitter_login);
mTwitterButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.equals(mTwitterButton)) {
mTwitter.authorize(this, new DialogListener() {
#Override
public void onComplete(String accessKey, String accessSecret) {
access_token = accessKey;
access_token_secret = accessSecret;
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Success")
.setMessage("access_key: " + accessKey
+ "\naccess_secret: " + accessSecret)
.setPositiveButton("Ok", null);
AlertDialog alert = builder.create();
alert.show();
new Item(MainActivity.this, accessKey, accessSecret);
}
#Override
public void onCancel() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Canceled")
.setMessage("Twitter Login Canceled")
.setPositiveButton("Ok", null);
AlertDialog alert = builder.create();
alert.show();
}
#Override
public void onError(TwitterError error) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Error")
.setMessage(error.getMessage())
.setPositiveButton("Ok", null);
AlertDialog alert = builder.create();
alert.show();
}
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Twitter Auth Callback
mTwitter.authorizeCallback(requestCode, resultCode, data);
}
}
Item.java:
package com.android.twitterapi;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.api.TweetsResources;
import twitter4j.auth.AccessToken;
import twitter4j.conf.ConfigurationBuilder;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
public class Item {
Activity mActivity;
String access_token;
String access_token_secret;
public Item(Activity activity, String key, String secret ) {
mActivity = activity;
access_token = key;
access_token_secret = secret;
new updateTwitterStatus().execute("Om Sri Sri Sri Veerabhadra Swamy");
}
/**
* Function to update status
* */
class updateTwitterStatus extends AsyncTask<String, String, String> {
ProgressDialog pDialog;
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(mActivity);
pDialog.setMessage("Updating to twitter...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Places JSON
* */
protected String doInBackground(String... args) {
Log.d("Tweet Text", "> " + args[0]);
String status = args[0];
try {
ConfigurationBuilder builder = new ConfigurationBuilder();
builder.setOAuthConsumerKey(MainActivity.CONSUMER_KEY);
builder.setOAuthConsumerSecret(MainActivity.CONSUMER_SECRET);
// Access Token
AccessToken accessToken = new AccessToken(access_token, access_token_secret);
Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
// Update status
twitter4j.Status response = ((TweetsResources) twitter).updateStatus(status);
Log.d("Status", "> " + response.getText());
} catch (TwitterException e) {
// Error in updating status
Log.d("Twitter Update Error", e.getMessage());
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog and show
* the data in UI Always use runOnUiThread(new Runnable()) to update UI
* from background thread, otherwise you will get error
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// // updating UI from Background Thread
// runOnUiThread(new Runnable() {
// #Override
// public void run() {
Toast.makeText(mActivity,
"Status tweeted successfully", Toast.LENGTH_SHORT)
.show();
// Clearing EditText field
//// txtUpdate.setText("");
// }
// });
}
}
}
Twitter.java:
package me.grantland.twitter;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
/**
* #author Grantland Chew
*/
public class Twitter {
public static final String TAG = "me.grantland.twitter";
public static final boolean DEBUG = false;
public static final String REQUEST_TOKEN = "https://twitter.com/oauth/request_token";
public static final String ACCESS_TOKEN = "https://twitter.com/oauth/access_token";
public static final String AUTHORIZE = "https://twitter.com/oauth/authorize";
public static final String DENIED = "denied";
public static final String CALLBACK_SCHEME = "gc";
public static final String CALLBACK_URI = CALLBACK_SCHEME + "://twitt";
public static final String EXTRA_ERROR = "error";
public static final String EXTRA_CONSUMER = "consumer";
public static final String EXTRA_AUTHORIZE_PARAMS = "params";
public static final String EXTRA_ACCESS_KEY = "access_key";
public static final String EXTRA_ACCESS_SECRET = "access_secret";
// Used as default activityCode by authorize(). See authorize() below.
public static final int DEFAULT_AUTH_ACTIVITY_CODE = 4242;
private OAuthConsumer mConsumer = null;
private int mRequestCode;
private DialogListener mListener = null;
public Twitter(String consumerKey, String consumerSecret) {
if (consumerKey == null || consumerSecret == null) {
throw new IllegalArgumentException(
"You must specify your consumer key and secret when instantiating " +
"a Twitter object. See README for details.");
}
mConsumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
}
/**
* Short authorize method that uses default settings.
*
* Starts either an activity or dialog that a user will use to enter their credentials
* to authorize your application with Twitter.
*
* #param activity
* The Activity to display the authorization window on.
* #param listener
* The callback for Twitter authentication responses.
* #return
*/
public boolean authorize(Activity activity, final DialogListener listener) {
return authorize(activity, false, null, DEFAULT_AUTH_ACTIVITY_CODE, listener);
}
/**
* Short authorize method that uses the default activityCode.
*
* Starts either an activity or dialog that a user will use to enter their credentials
* to authorize your application with Twitter.
*
* #param activity
* The Activity to display the authorization window on.
* #param forceLogin
* Forces the user to enter their credentials to ensure the correct users account
* is authorized.
* #param screenName
* Prefills the username input box of the OAuth login screen with the given value.
* #param listener
* The callback for Twitter authentication responses.
* #return
*/
public boolean authorize(Activity activity, boolean forceLogin, String screenName, DialogListener listener) {
return authorize(activity, forceLogin, screenName, DEFAULT_AUTH_ACTIVITY_CODE, listener);
}
/**
* Full authorize method.
*
* Starts either an activity or dialog that a user will use to enter their credentials
* to authorize your application with Twitter.
*
* #param activity
* The Activity to display the authorization window on.
* #param forceLogin
* Forces the user to enter their credentials to ensure the correct users account
* is authorized.
* #param screenName
* Prefills the username input box of the OAuth login screen with the given value.
* #param activityCode
* The requestCode used in Activity#onActivityResult. Can be changed if the default
* conflicts with another Activity in your application.
* #param listener
* The callback for Twitter authentication responses.
* #return
*/
public boolean authorize(Activity activity, boolean forceLogin, String screenName, int activityCode, DialogListener listener) {
// Optional params
String authorizeParams = "";
if (forceLogin) {
authorizeParams += "?force_login=" + forceLogin;
}
if (screenName != null) {
authorizeParams += (authorizeParams.length() == 0 ? "&" : "?") + "screen_name=" + screenName;
}
if (DEBUG) Log.d(TAG, "authorize params: " + authorizeParams);
// We could check if the activity exists in the manifest and fallback on
// the dialog, but if a user wants to use the dialog they can.
if (activityCode > 0) {
startTwitterActivity(activity, authorizeParams, activityCode, listener);
} else {
startTwitterDialog(activity, authorizeParams, listener);
}
return true;
}
private boolean startTwitterActivity(Activity activity, String authorizeParams, int activityCode, DialogListener listener) {
mRequestCode = activityCode;
mListener = listener;
Intent intent = new Intent(activity, TwitterActivity.class);
intent.putExtra(EXTRA_CONSUMER, mConsumer);
intent.putExtra(EXTRA_AUTHORIZE_PARAMS, authorizeParams);
activity.startActivityForResult(intent, DEFAULT_AUTH_ACTIVITY_CODE);
return true;
}
private boolean startTwitterDialog(Activity activity, String authorizeParams, final DialogListener listener) {
TwitterDialog dialog = new TwitterDialog(activity, mConsumer, authorizeParams, new DialogListener() {
#Override
public void onComplete(String token, String secret) {
if (DEBUG) Log.d(TAG, "access_key: " + token);
if (DEBUG) Log.d(TAG, "access_secret: " + secret);
mConsumer.setTokenWithSecret(token, secret);
listener.onComplete(token, token);
}
#Override
public void onError(TwitterError error) {
listener.onError(error);
}
#Override
public void onCancel() {
listener.onCancel();
}
});
dialog.show();
return true;
}
/**
* Callback for Twitter authorize. Should be called in any Activity that calls
* Twitter#authorize.
*
* #param requestCode
* The integer request code originally supplied to
* startActivityForResult(), allowing you to identify who this
* result came from.
* #param resultCode
* The integer result code returned by the child activity
* through its setResult().
* #param data
* An Intent, which can return result data to the caller
* (various data can be attached to Intent "extras").
*/
public void authorizeCallback(int requestCode, int resultCode, Intent data) {
if (mRequestCode != requestCode) {
return;
}
String accessKey, accessSecret;
if (Activity.RESULT_OK == resultCode) {
String error = data.getStringExtra(EXTRA_ERROR);
if (error != null) {
mListener.onError(new TwitterError(error));
} else {
accessKey = data.getStringExtra(EXTRA_ACCESS_KEY);
accessSecret = data.getStringExtra(EXTRA_ACCESS_SECRET);
if (DEBUG) Log.d(TAG, "access_key: " + accessKey);
if (DEBUG) Log.d(TAG, "access_secret: " + accessSecret);
mConsumer.setTokenWithSecret(accessKey, accessSecret);
if (mListener != null) {
mListener.onComplete(accessKey, accessSecret);
return;
}
}
} else if (Activity.RESULT_CANCELED == resultCode) {
if (mListener != null) {
mListener.onCancel();
}
}
}
//==============================================================================================
// Properties
//==============================================================================================
/**
* #return boolean - whether this object has an non-expired session token.
*/
public boolean isSessionValid() {
return mConsumer != null && (getAccessToken() != null && getAccessTokenSecret() != null);
}
/**
* #return String - the consumer_key.
*/
public String getConsumerKey() {
return mConsumer.getConsumerKey();
}
/**
* #return String - the consumer_secret.
*/
public String getConsumerSecret() {
return mConsumer.getConsumerSecret();
}
/**
* Sets the consumer_key and consumer_secret.
* #param consumerKey
* #param consumerSecret
*/
public void setConsumerKeyAndSecret(String consumerKey, String consumerSecret) {
mConsumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
}
/**
* #return String - the access_token.
*/
public String getAccessToken() {
return mConsumer.getToken();
}
/**
* #return String - the access_token_secret.
*/
public String getAccessTokenSecret() {
return mConsumer.getTokenSecret();
}
/**
* Sets the access_token and access_token_secret.
* #param token
* #param secret
*/
public void setTokenWithSecret(String token, String secret) {
mConsumer.setTokenWithSecret(token, secret);
}
/**
* Callback interface for dialog requests.
*/
public static interface DialogListener {
/**
* Called when a dialog completes.
*
* Executed by the thread that initiated the dialog.
*
* #param values
* Key-value string pairs extracted from the response.
*/
public void onComplete(String accessKey, String accessSecret);
/**
* Called when a dialog has an error.
*
* Executed by the thread that initiated the dialog.
*/
public void onError(TwitterError error);
/**
* Called when a dialog is canceled by the user.
*
* Executed by the thread that initiated the dialog.
*/
public void onCancel();
}
}
TwitterActivity.java:
package me.grantland.twitter;
import oauth.signpost.OAuth;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import oauth.signpost.exception.OAuthException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.android.twitterapi.R;
public class TwitterActivity extends Activity {
private static final String TAG = Twitter.TAG;
private static final boolean DEBUG = Twitter.DEBUG;
private static final int RETRIEVE_REQUEST_TOKEN = 1;
private static final int RETRIEVE_ACCESS_TOKEN = 2;
private static final String KEY_URL = "url";
private H mMainThreadHandler;
private OAuthConsumer mConsumer;
private OAuthProvider mProvider;
private ProgressDialog mSpinner;
private WebView mWebView;
/**
* Handler to run shit on the UI thread
*
* #author Grantland Chew
*/
private class H extends Handler {
#Override
public void handleMessage (Message msg) {
Bundle data = msg.getData();
switch (msg.what) {
case RETRIEVE_REQUEST_TOKEN: {
mWebView.loadUrl(data.getString(KEY_URL));
} break;
case RETRIEVE_ACCESS_TOKEN: {
} break;
default: {
}
}
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.twitter_layout);
Intent intent = getIntent();
mConsumer = (OAuthConsumer)intent.getSerializableExtra(Twitter.EXTRA_CONSUMER);
String authorizeParams = intent.getStringExtra(Twitter.EXTRA_AUTHORIZE_PARAMS);
mMainThreadHandler = new H();
mProvider = new CommonsHttpOAuthProvider(
Twitter.REQUEST_TOKEN,
Twitter.ACCESS_TOKEN,
Twitter.AUTHORIZE + authorizeParams);
mProvider.setOAuth10a(true);
mSpinner = new ProgressDialog(this);
mSpinner.setMessage(getResources().getString(R.string.loading_loading));
mSpinner.setOnCancelListener(new OnCancelListener() {
#Override public void onCancel(DialogInterface dialog) {
cancel();
}
});
mWebView = (WebView)findViewById(R.id.twitter_webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setSaveFormData(false);
mWebView.getSettings().setSavePassword(false);
mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
mWebView.setWebViewClient(new TwitterWebViewClient());
// Retrieve request_token on background thread
Thread thread = new Thread() {
#Override
public void run() {
try {
Message msg = new Message();
msg.what = RETRIEVE_REQUEST_TOKEN;
Bundle bundle = new Bundle();
bundle.putString(KEY_URL, mProvider.retrieveRequestToken(mConsumer, Twitter.CALLBACK_URI));
msg.setData(bundle);
if (DEBUG) Log.d(TAG, "url: " + bundle.getString(KEY_URL));
mMainThreadHandler.sendMessage(msg);
} catch (OAuthException e) {
error(e);
}
}
};
thread.start();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (KeyEvent.KEYCODE_BACK == keyCode) {
cancel();
return true; // consume event
}
return false; // don't consume event
}
private void error(Throwable error) {
Intent intent = this.getIntent();
intent.putExtra(Twitter.EXTRA_ERROR, error.getMessage());
this.setResult(RESULT_OK, intent);
finish();
}
private void cancel() {
Intent intent = this.getIntent();
this.setResult(RESULT_CANCELED, intent);
finish();
}
private void complete(String accessKey, String accessSecret) {
Intent intent = this.getIntent();
intent.putExtra(Twitter.EXTRA_ACCESS_KEY, accessKey);
intent.putExtra(Twitter.EXTRA_ACCESS_SECRET, accessSecret);
this.setResult(RESULT_OK, intent);
finish();
}
private void retrieveAccessToken(final Uri uri) {
Thread thread = new Thread() {
#Override
public void run() {
try {
if (DEBUG) Log.d(TAG, uri.toString());
String oauth_token = uri.getQueryParameter(OAuth.OAUTH_TOKEN);
String verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
if (DEBUG) Log.d(TAG, oauth_token);
if (DEBUG) Log.d(TAG, verifier);
mConsumer.setTokenWithSecret(oauth_token, mConsumer.getConsumerSecret());
mProvider.retrieveAccessToken(mConsumer, verifier);
complete(mConsumer.getToken(), mConsumer.getTokenSecret());
} catch (OAuthException e) {
error(e);
}
}
};
thread.start();
}
private class TwitterWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (DEBUG) Log.d(TAG, url);
Uri uri = Uri.parse(url);
if (uri != null && Twitter.CALLBACK_SCHEME.equals(uri.getScheme())) {
String denied = uri.getQueryParameter(Twitter.DENIED);
if (denied != null) {
cancel();
} else {
retrieveAccessToken(uri);
}
return true;
}
return false;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
if (DEBUG) Log.d(TAG, "Webview loading URL: " + url);
if (view.getVisibility() != View.INVISIBLE && !mSpinner.isShowing()) {
mSpinner.show();
}
}
#Override
public void onPageFinished(WebView view, String url) {
mSpinner.dismiss();
view.setVisibility(View.VISIBLE);
}
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
error(new TwitterError(description, errorCode, failingUrl));
}
};
}
I recommend you use this library. This library as explained in the book "Learning Android, 2nd Edition": It has been stripped down to the bare essentials, making it easy for you to peek at it's source code and see it's inner workings, if you care to do so. It also supports Twitter’s older API that allows for simple authentication (username and password) versus the new OAuth authentication. is much simpler to integrate and use than the one you are using. Again it depends what you want to actually do. if your purpose is to learn and you are new to Java and Android this is recommended due to focus on learning the concept rather than library and API.
I can recommend you this library - https://github.com/antonkrasov/AndroidSocialNetworks
But your issue in permission of your app.
Open your app settings and go to permissions tab:
Then select Read and Write and save:
Now all should work.
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);