I want to sync the local database file in the Android app with the users' DropBox or SkyDrive account. Anything would do.
I am not able to get a running code.
Please help.
Here is the code I got from the official DropBox site, but it says error at
"final static private AccessType ACCESS_TYPE = AccessType.APP_FOLDER;" as NoClassDefFoundError
public class DBRoulette extends Activity {
private static final String TAG = "DBRoulette";
///////////////////////////////////////////////////////////////////////////
// Your app-specific settings. //
///////////////////////////////////////////////////////////////////////////
// Replace this with your app key and secret assigned by Dropbox.
// Note that this is a really insecure way to do this, and you shouldn't
// ship code which contains your key & secret in such an obvious way.
// Obfuscation is good.
final static private String APP_KEY = "5gqlcpeirbe9kju";
final static private String APP_SECRET = "zs9bi3nwqf4arn2";
// If you'd like to change the access type to the full Dropbox instead of
// an app folder, change this value.
final static private AccessType ACCESS_TYPE = AccessType.APP_FOLDER;
///////////////////////////////////////////////////////////////////////////
// End app-specific settings. //
///////////////////////////////////////////////////////////////////////////
// You don't need to change these, leave them alone.
final static private String ACCOUNT_PREFS_NAME = "prefs";
final static private String ACCESS_KEY_NAME = "ACCESS_KEY";
final static private String ACCESS_SECRET_NAME = "ACCESS_SECRET";
DropboxAPI<AndroidAuthSession> mApi;
private boolean mLoggedIn;
// Android widgets
private Button mSubmit;
private LinearLayout mDisplay;
private Button mPhoto;
private Button mRoulette;
private ImageView mImage;
private final String PHOTO_DIR = "/Photos/";
final static private int NEW_PICTURE = 1;
private String mCameraFileName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
mCameraFileName = savedInstanceState.getString("mCameraFileName");
}
// We create a new AuthSession so that we can use the Dropbox API.
AndroidAuthSession session = buildSession();
mApi = new DropboxAPI<AndroidAuthSession>(session);
// Basic Android widgets
setContentView(R.layout.main);
checkAppKeySetup();
mSubmit = (Button)findViewById(R.id.auth_button);
mSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// This logs you out if you're logged in, or vice versa
if (mLoggedIn) {
logOut();
} else {
// Start the remote authentication
mApi.getSession().startAuthentication(DBRoulette.this);
}
}
});
mDisplay = (LinearLayout)findViewById(R.id.logged_in_display);
// This is where a photo is displayed
mImage = (ImageView)findViewById(R.id.image_view);
// This is the button to take a photo
mPhoto = (Button)findViewById(R.id.photo_button);
mPhoto.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
// Picture from camera
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
// This is not the right way to do this, but for some reason, having
// it store it in
// MediaStore.Images.Media.EXTERNAL_CONTENT_URI isn't working right.
Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd-kk-mm-ss");
String newPicFile = df.format(date) + ".jpg";
String outPath = "/sdcard/" + newPicFile;
File outFile = new File(outPath);
mCameraFileName = outFile.toString();
Uri outuri = Uri.fromFile(outFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outuri);
Log.i(TAG, "Importing New Picture: " + mCameraFileName);
try {
startActivityForResult(intent, NEW_PICTURE);
} catch (ActivityNotFoundException e) {
showToast("There doesn't seem to be a camera.");
}
}
});
// This is the button to take a photo
mRoulette = (Button)findViewById(R.id.roulette_button);
mRoulette.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
DownloadRandomPicture download = new DownloadRandomPicture(DBRoulette.this, mApi, PHOTO_DIR, mImage);
download.execute();
}
});
// Display the proper UI state if logged in or not
setLoggedIn(mApi.getSession().isLinked());
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString("mCameraFileName", mCameraFileName);
super.onSaveInstanceState(outState);
}
#Override
protected void onResume() {
super.onResume();
AndroidAuthSession session = mApi.getSession();
// The next part must be inserted in the onResume() method of the
// activity from which session.startAuthentication() was called, so
// that Dropbox authentication completes properly.
if (session.authenticationSuccessful()) {
try {
// Mandatory call to complete the auth
session.finishAuthentication();
// Store it locally in our app for later use
TokenPair tokens = session.getAccessTokenPair();
storeKeys(tokens.key, tokens.secret);
setLoggedIn(true);
} catch (IllegalStateException e) {
showToast("Couldn't authenticate with Dropbox:" + e.getLocalizedMessage());
Log.i(TAG, "Error authenticating", e);
}
}
}
// This is what gets called on finishing a media piece to import
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == NEW_PICTURE) {
// return from file upload
if (resultCode == Activity.RESULT_OK) {
Uri uri = null;
if (data != null) {
uri = data.getData();
}
if (uri == null && mCameraFileName != null) {
uri = Uri.fromFile(new File(mCameraFileName));
}
File file = new File(mCameraFileName);
if (uri != null) {
UploadPicture upload = new UploadPicture(this, mApi, PHOTO_DIR, file);
upload.execute();
}
} else {
Log.w(TAG, "Unknown Activity Result from mediaImport: "
+ resultCode);
}
}
}
private void logOut() {
// Remove credentials from the session
mApi.getSession().unlink();
// Clear our stored keys
clearKeys();
// Change UI state to display logged out version
setLoggedIn(false);
}
/**
* Convenience function to change UI state based on being logged in
*/
private void setLoggedIn(boolean loggedIn) {
mLoggedIn = loggedIn;
if (loggedIn) {
mSubmit.setText("Unlink from Dropbox");
mDisplay.setVisibility(View.VISIBLE);
} else {
mSubmit.setText("Link with Dropbox");
mDisplay.setVisibility(View.GONE);
mImage.setImageDrawable(null);
}
}
private void checkAppKeySetup() {
// Check to make sure that we have a valid app key
if (APP_KEY.startsWith("CHANGE") ||
APP_SECRET.startsWith("CHANGE")) {
showToast("You must apply for an app key and secret from developers.dropbox.com, and add them to the DBRoulette ap before trying it.");
finish();
return;
}
// Check if the app has set up its manifest properly.
Intent testIntent = new Intent(Intent.ACTION_VIEW);
String scheme = "db-" + APP_KEY;
String uri = scheme + "://" + AuthActivity.AUTH_VERSION + "/test";
testIntent.setData(Uri.parse(uri));
PackageManager pm = getPackageManager();
if (0 == pm.queryIntentActivities(testIntent, 0).size()) {
showToast("URL scheme in your app's " +
"manifest is not set up correctly. You should have a " +
"com.dropbox.client2.android.AuthActivity with the " +
"scheme: " + scheme);
finish();
}
}
private void showToast(String msg) {
Toast error = Toast.makeText(this, msg, Toast.LENGTH_LONG);
error.show();
}
/**
* Shows keeping the access keys returned from Trusted Authenticator in a local
* store, rather than storing user name & password, and re-authenticating each
* time (which is not to be done, ever).
*
* #return Array of [access_key, access_secret], or null if none stored
*/
private String[] getKeys() {
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
String key = prefs.getString(ACCESS_KEY_NAME, null);
String secret = prefs.getString(ACCESS_SECRET_NAME, null);
if (key != null && secret != null) {
String[] ret = new String[2];
ret[0] = key;
ret[1] = secret;
return ret;
} else {
return null;
}
}
/**
* Shows keeping the access keys returned from Trusted Authenticator in a local
* store, rather than storing user name & password, and re-authenticating each
* time (which is not to be done, ever).
*/
private void storeKeys(String key, String secret) {
// Save the access key for later
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
Editor edit = prefs.edit();
edit.putString(ACCESS_KEY_NAME, key);
edit.putString(ACCESS_SECRET_NAME, secret);
edit.commit();
}
private void clearKeys() {
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
Editor edit = prefs.edit();
edit.clear();
edit.commit();
}
private AndroidAuthSession buildSession() {
AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session;
String[] stored = getKeys();
if (stored != null) {
AccessTokenPair accessToken = new AccessTokenPair(stored[0], stored[1]);
session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE, accessToken);
} else {
session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE);
}
return session;
}
}
Do you add the dropbox-android-sdk.jar in your buildPath and in a correct way ?
The DropboxAPI JAR file should be in the libs/ folder, not lib/.
Try this and tell me if it works now ...
PS: I'm working with DropboxAPI for android, and their code works very well for me and their documentation is really good to do your own application.
Related
I'm using agora to make voice calls in my android application , i have set up the code as per the documentation but whenever i try to join a call it crashes and says that rtcEngine is null even though it is initialized , any help would be appreciated , Thank you
Code
public class AudioCallActivity extends AppCompatActivity {
// An integer that identifies the local user.
private int uid = 0;
// Track the status of your connection
private boolean isJoined = false;
// Agora engine instance
private RtcEngine agoraEngine;
// UI elements
private TextView infoText;
private Button joinLeaveButton;
private static final int PERMISSION_REQ_ID = 22;
private static final String[] REQUESTED_PERMISSIONS = { Manifest.permission.RECORD_AUDIO};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_audio_call);
// If all the permissions are granted, initialize the RtcEngine object and join a channel.
if (!checkSelfPermission()) {
ActivityCompat.requestPermissions(this, REQUESTED_PERMISSIONS, PERMISSION_REQ_ID);
}
setupVoiceSDKEngine();
// Set up access to the UI elements
joinLeaveButton = findViewById(R.id.joinLeaveButton);
infoText = findViewById(R.id.infoText);
}
private boolean checkSelfPermission() {
return ContextCompat.checkSelfPermission(this, REQUESTED_PERMISSIONS[0]) == PackageManager.PERMISSION_GRANTED;
}
void showMessage(String message) {
runOnUiThread(() -> Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show());
}
private void setupVoiceSDKEngine() {
try {
RtcEngineConfig config = new RtcEngineConfig();
config.mContext = getBaseContext();
config.mAppId = getString(R.string.app_id);
config.mEventHandler = mRtcEventHandler;
agoraEngine = RtcEngine.create(config);
} catch (Exception e) {
throw new RuntimeException("Check the error.");
}
}
private final IRtcEngineEventHandler mRtcEventHandler = new IRtcEngineEventHandler() {
#Override
// Listen for the remote user joining the channel.
public void onUserJoined(int uid, int elapsed) {
runOnUiThread(()->infoText.setText("Remote user joined: " + uid));
}
#Override
public void onJoinChannelSuccess(String channel, int uid, int elapsed) {
// Successfully joined a channel
isJoined = true;
showMessage("Joined Channel " + channel);
runOnUiThread(()->infoText.setText("Waiting for a remote user to join"));
}
#Override
public void onUserOffline(int uid, int reason) {
// Listen for remote users leaving the channel
showMessage("Remote user offline " + uid + " " + reason);
if (isJoined) runOnUiThread(()->infoText.setText("Waiting for a remote user to join"));
}
#Override
public void onLeaveChannel(RtcStats stats) {
// Listen for the local user leaving the channel
runOnUiThread(()->infoText.setText("Press the button to join a channel"));
isJoined = false;
}
};
private void joinChannel() {
ChannelMediaOptions options = new ChannelMediaOptions();
options.autoSubscribeAudio = true;
// Set both clients as the BROADCASTER.
options.clientRoleType = Constants.CLIENT_ROLE_BROADCASTER;
// Set the channel profile as BROADCASTING.
options.channelProfile = Constants.CHANNEL_PROFILE_LIVE_BROADCASTING;
// Join the channel with a temp token.
// You need to specify the user ID yourself, and ensure that it is unique in the channel.
agoraEngine.joinChannel(getString(R.string.agora_token), "ChannelOne", uid, options);
}
public void joinLeaveChannel(View view) {
try {
if (isJoined) {
agoraEngine.leaveChannel();
joinLeaveButton.setText("Join");
} else {
joinChannel();
joinLeaveButton.setText("Leave");
}
}catch (Exception e){
Log.d("TAG","Error is " + e.getMessage());
}
}
#Override
protected void onDestroy() {
agoraEngine.leaveChannel();
// Destroy the engine in a sub-thread to avoid congestion
new Thread(() -> {
RtcEngine.destroy();
agoraEngine = null;
}).start();
onDestroy();
}
}
Error Thrown
Attempt to invoke virtual method 'int io.agora.rtc2.RtcEngine.joinChannel(java.lang.String, java.lang.String, int, io.agora.rtc2.ChannelMediaOptions)' on a null object reference
I'm new to Android development and I have been following a tutorial which creates a Twitter application that shows the users timeline and gives them to ability to reply and retweet Tweets for people they follow.
I have completed that tutorial, and I am now trying to implement Direct Messaging into the application. So far I have got my application to display the users timeline and a list of direct messages they have received, but when the user clicks between the main activity which displays their timeline, and their inbox eventually the application crashes.
The error message is as follows:
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: messageInbox._id (code 1555 SQLITE_CONSTRAINT_PRIMARYKEY[1555])
I've searched for the error code and solutions online and so far have no luck with it. I'd be grateful for any help in resolving this, and also any other pointers related to the code I have here as I am new to Java.
It's running on Android 9 and besides some deprecated methods, I have used AndroidX.
The error occurs when the insertOrThrow method below is called in my MessageService class
try{
int count = 50;
DirectMessageList directMessages = messageTwitter.getDirectMessages(count);
for(DirectMessage message : directMessages){
ContentValues messageValues = MessageDataHelper.getValues(message);
messageDB.insertOrThrow("messageInbox", null, messageValues);
messagesChanges = true;
}
} catch (TwitterException te) {
String LOG_TAG = "MessageService";
Log.e(LOG_TAG, "Exception: " + te);
MessageService Class
public class MessageService extends Service {
//twitter authentication key
public final static String TWIT_KEY = "XXXXXXXXXX";
//twitter secret
public final static String TWIT_SECRET = "XXXXXXXXXX";
//app preferences
SharedPreferences bioPrefs;
//twitter object
private Twitter messageTwitter;
//database helper object
private MessageDataHelper messageHelper;
//timeline database
private SQLiteDatabase messageDB;
//handler for updater
public Handler messageHandler;
//delay between fetching new tweets
//private static int mins = 1;//alter to suit
//private static final long FETCH_DELAY = mins * (60*1000);
private static final long FETCH_DELAY = 30000;//Update timeline every 30 seconds
//updater thread object
private MessageUpdater messageUpdater;
#Override
public void onCreate(){
super.onCreate();
//Setting up the class
//get preferences
//shared preferences for user details
bioPrefs = getSharedPreferences("bioPrefs", 0);
//get user preferences
String userToken = bioPrefs.getString("user_token", null);
String userSecret = bioPrefs.getString("user_secret", null);
//get database helper
//database helper object
messageHelper = new MessageDataHelper(this);
//get the database
messageDB = messageHelper.getWritableDatabase();
//create new configuration
Configuration messageConf = new ConfigurationBuilder()
.setOAuthConsumerKey(TWIT_KEY)
.setOAuthConsumerSecret(TWIT_SECRET)
.setOAuthAccessToken(userToken)
.setOAuthAccessTokenSecret(userSecret)
.build();
//instantiate new twitter
messageTwitter = new TwitterFactory(messageConf).getInstance();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
private class MessageUpdater implements Runnable{
public void run(){
boolean messagesChanges = false;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try{
int count = 50;
DirectMessageList directMessages = messageTwitter.getDirectMessages(count);
for(DirectMessage message : directMessages){
ContentValues messageValues = MessageDataHelper.getValues(message);
messageDB.insertOrThrow("messageInbox", null, messageValues);
messagesChanges = true;
}
} catch (TwitterException te) {
String LOG_TAG = "MessageService";
Log.e(LOG_TAG, "Exception: " + te);}
if(messagesChanges){
sendBroadcast(new Intent("MESSAGE_UPDATES"));
}
messageHandler.postDelayed(this, FETCH_DELAY);
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStart(intent, startId);
//get handler
messageHandler = new Handler();
//create an instance of the updater class
messageUpdater = new MessageUpdater();
//add to run queue
messageHandler.post(messageUpdater);
//return sticky
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
//stop the updating
messageHandler.removeCallbacks(messageUpdater);
messageDB.close();
}
}
MessageDataHelper Class
public class MessageDataHelper extends SQLiteOpenHelper {
//Variable Declarations
//db version
private static final int DB_VERSION = 1;
//database name
private static final String DATABASE_NAME = "messageInbox.db";
//ID column
private static final String Home_COL = BaseColumns._ID;
//tweet text
private static final String Update_COL = "message_text";
//twitter screen name
private static final String User_COL = "user_screen";
//time tweeted
private static final String Time_COL = "message_time";
//user profile image
//private static final String User_IMG = "user_img";
//database creation string
private static final String DATABASE_CREATE = "CREATE TABLE messageInbox (" + Home_COL + " INTEGER PRIMARY KEY AUTOINCREMENT, " + Update_COL + " TEXT, "
+ User_COL + " TEXT, " + Time_COL + " INTEGER);";
//" , " +
//+ User_IMG + " TEXT);";
MessageDataHelper(Context context){
super(context, DATABASE_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS messageInbox");
sqLiteDatabase.execSQL("VACUUM");
onCreate(sqLiteDatabase);
}
static ContentValues getValues(DirectMessage message){
ContentValues messageValues = new ContentValues();
//get the values
try {
//get each value from the table
messageValues.put(Home_COL, message.getId());
messageValues.put(Update_COL, message.getText());
messageValues.put(User_COL, message.getSenderId());
messageValues.put(Time_COL, message.getCreatedAt().getTime());
//noinspection StringOperationCanBeSimplified
//messageValues.put(User_IMG, message.getSender().getProfileImageURL().toString());
}
catch(Exception te) { Log.e("MessageDataHelper", te.getMessage()); }
//return the values
return messageValues;
}
}
MessageActivity
public class MessageActivity extends AppCompatActivity implements View.OnClickListener {
//Variable declarations
//app url
public final static String TWIT_URL = "bioauth://";
//Twitter instance
private Twitter bioMessaging;
//request token for accessing user account
private RequestToken messageRequestToken;
//shared preferences to store user details
private SharedPreferences messagePrefs;
//main view for the inbox
private ListView messageInbox;
//update database
private SQLiteDatabase inboxDB;
//cursor for handling data
private Cursor inboxCursor;
//adapter for mapping data
private MessageAdapter messageAdapter;
//for error logging
private String LOG_TAG = "MessageActivity";
//Broadcast receiver for when new updates are available
private BroadcastReceiver messageStatusReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Sets the inbox layout style using inbox_layout.xml
setContentView(R.layout.inbox_layout);
//setup onclick listener for tweet button
LinearLayout newMessageClicker = findViewById(R.id.newmessagebutton);
newMessageClicker.setOnClickListener(this);
LinearLayout timelineClicker = findViewById(R.id.timelineButton);
timelineClicker.setOnClickListener(this);
//get the preferences for the app
messagePrefs = getSharedPreferences("bioPrefs", 0);
//get user token and secret for authentication
//String userToken = messagePrefs.getString("user_token", null);
//String userSecret = messagePrefs.getString("user_secret", null);
}
//Click listener handles sign in and tweet button presses
public void onClick(View v) {
//find view
switch(v.getId()) {
//user has pressed tweet button
case R.id.newmessagebutton:
//launch tweet activity
startActivity(new Intent(this, DirectMessageClass.class));
break;
case R.id.timelineButton:
//Return to timeline
finish();
//startActivity(new Intent(this, MainActivity.class));
break;
default:
break;
}
}
//setupInbox displays the user's Twitter messages
private void setupInbox() {
//setContentView(R.layout.inbox_layout); //Sets the inbox layout style using inbox_layout.xml
/*//setup onclick listener for tweet button
LinearLayout newMessageClicker = findViewById(R.id.newmessagebutton);
newMessageClicker.setOnClickListener(this);
LinearLayout timelineClicker = findViewById(R.id.timelineButton);
timelineClicker.setOnClickListener(this);*/
//Error catching
try {
//get the inbox
//get reference to the list view
messageInbox = findViewById(R.id.messageList);
//instantiate database helper
//database helper for update data
MessageDataHelper messageHelper = new MessageDataHelper(this);
//get the database
inboxDB = messageHelper.getReadableDatabase();
//query the database, most recent tweets first
inboxCursor = inboxDB.query
("messageInbox", null, null, null, null, null, "message_time DESC");
//manage the updates using a cursor
startManagingCursor(inboxCursor);
//instantiate adapter
messageAdapter = new MessageAdapter(this, inboxCursor);
//this will make the app populate the new update data in the timeline view
messageInbox.setAdapter(messageAdapter);
//instantiate receiver class for finding out when new updates are available
messageStatusReceiver = new TwitterUpdateReceiver();
//register for updates
registerReceiver(messageStatusReceiver, new IntentFilter("MESSAGE_UPDATES"));
//start the Service for updates now
this.getApplicationContext().startService(new Intent(this.getApplicationContext(), MessageService.class));
}
catch(Exception te) {
Log.e(LOG_TAG, "Failed to fetch inbox: " + te.getMessage());
notifyUser("Failed to fetch inbox");
}
}
//Class to implement Broadcast receipt for new updates
class TwitterUpdateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
int rowLimit = 50;
if(DatabaseUtils.queryNumEntries(inboxDB, "messageInbox")>rowLimit) {
String deleteQuery = "DELETE FROM messageInbox WHERE "+ BaseColumns._ID+" NOT IN " +
"(SELECT "+BaseColumns._ID+" FROM messageInbox ORDER BY "+"message_time DESC " +
"limit "+rowLimit+")";
inboxDB.execSQL(deleteQuery);
}
inboxCursor = inboxDB.query("messageInbox", null, null, null, null, null, "message_time DESC");
startManagingCursor(inboxCursor);
messageAdapter = new MessageAdapter(context, inboxCursor);
messageInbox.setAdapter(messageAdapter);
}
}
#Override
public void onDestroy() {
super.onDestroy();
try {
//stop the updater Service
stopService(new Intent(this, MessageService.class));
//remove receiver register
unregisterReceiver(messageStatusReceiver);
//close the database
inboxDB.close();
}
catch(Exception se) { Log.e(LOG_TAG, "unable to stop Service or receiver"); }
}
//Method to output inbox_layout to user
private void notifyUser(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
MessageAdapter Class
public class MessageAdapter extends SimpleCursorAdapter {
//Twitter developer key
//private final static String TWIT_KEY = "XXXXXXXXXX";
//Twitter developer secret
//private final static String TWIT_SECRET = "XXXXXXXXXX";
//strings representing database column names to map to views
private static final String[] from = { "message_text", "user_screen",
"message_time" };
//view item IDs for mapping database record values to
private static final int[] to = { R.id.messageText, R.id.userScreen,
R.id.messageTime,};
//constructor sets up adapter, passing 'from' data and 'to' views
MessageAdapter(Context context, Cursor c) {
super(context, R.layout.direct_message, c, from, to);
}
//Bind the data to the visible views
#Override
public void bindView(View row, Context context, Cursor cursor) {
super.bindView(row, context, cursor);
//get the update time
long createdAt = cursor.getLong(cursor.getColumnIndex("message_time"));
//get the update time view
TextView textCreatedAt = row.findViewById(R.id.messageTime);
//adjust the way the time is displayed to make it human-readable
textCreatedAt.setText(DateUtils.getRelativeTimeSpanString(createdAt)+" ");
//get the status ID
long messageID = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID));
//get the user name
String messageName = cursor.getString(cursor.getColumnIndex("user_screen"));
//create a StatusData object to store these
StatusData messageData = new StatusData(messageID, messageName);
//set the status data object as tag for reply button in this view
row.findViewById(R.id.messageReply).setTag(messageData);
//setup onclick listeners for the retweet and reply buttons
row.findViewById(R.id.messageReply).setOnClickListener(messageListener);
//setup onclick for the user screen name within the tweet
row.findViewById(R.id.userScreen).setOnClickListener(messageListener);
}
// tweetListener handles clicks of reply and retweet buttons
// also handles clicking the user name within a tweet
private final View.OnClickListener messageListener = new View.OnClickListener() {
//onClick method
public void onClick(View v) {
//which view was clicked
switch (v.getId()) {
//message reply button pressed
case R.id.messageReply:
//implement reply
//create an intent for sending a new tweet
Intent messageReplyIntent = new Intent(v.getContext(), DirectMessageClass.class);
//get the data from the tag within the button view
StatusData messageData = (StatusData) v.getTag();
//pass the status ID
messageReplyIntent.putExtra("tweetID", messageData.getID());
//pass the user name
messageReplyIntent.putExtra("tweetUser", messageData.getUser());
//go to the tweet screen
v.getContext().startActivity(messageReplyIntent);
break;
case R.id.homebutton:
//Add return to timeline method
break;
default:
break;
}
}
};
}
Resolved the issue by using UNIQUE(" + Home_COL +") ON CONFLICT REPLACE when creating the table and insertWithOnConflict instead of insertOrThrow method.
Hi I'm quite new to Java, I wonder how to call a void method from another activity, when I already moved to new activity. For example, I want to call
onCreate(Bundle state)
from PocketSphinxActivty.java
in my new activity SMSReaderMain.java
I already tried
PocketSphinxActivity ps = new PocketSphinxActivity();
ps.onCreate(null);
It gives no error, but when SMSReaderMain.java activity start it suddenly force close and not responding in the actual device.
I also try to change into ps.onCreate(this) or ps.onCreate(SMSReaderMain.this) but it gives
The method setupRecognizer(File) in the type PocketSphinxActivity is not applicable for the arguments
(SMSReaderMain)
Here's the complete code, and I want to call almost all of method there in my new activity SMSReaderMain.java
PocketSphinxActivity.java
package edu.cmu.pocketsphinx.demo;
public class PocketSphinxActivity extends Activity implements
RecognitionListener {
//keyword yang digunakan dalem program untuk set ke even2 tertentu
private static final String KWS_SEARCH = "wakeup";
private static final String FORECAST_SEARCH = "forecast";
private static final String DIGITS_SEARCH = "drive mode";
private static final String MENU_SEARCH = "menu";
private static final String KEYPHRASE = "ok";
private SpeechRecognizer recognizer;
private HashMap<String, Integer> captions;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
// Buat nyiapin User Interface
captions = new HashMap<String, Integer>();
captions.put(KWS_SEARCH, R.string.kws_caption);
captions.put(MENU_SEARCH, R.string.menu_caption);
//captions.put(DIGITS_SEARCH, R.string.digits_caption);
captions.put(FORECAST_SEARCH, R.string.forecast_caption);
setContentView(R.layout.main);
((TextView) findViewById(R.id.caption_text))
.setText("Preparing the recognizer");
// Recognizer initialization is a time-consuming and it involves IO,
// so we execute it in async task
new AsyncTask<Void, Void, Exception>() {
#Override
protected Exception doInBackground(Void... params) {
try {
Assets assets = new Assets(PocketSphinxActivity.this);
File assetDir = assets.syncAssets();
setupRecognizer(assetDir);
} catch (IOException e) {
return e;
}
return null;
}
#Override
protected void onPostExecute(Exception result) {
if (result != null) {
((TextView) findViewById(R.id.caption_text))
.setText("Failed to init recognizer " + result);
} else {
switchSearch(KWS_SEARCH);
}
}
}.execute();
}
//nyocokin keyword dan pindah2 menu
#Override
public void onPartialResult(Hypothesis hypothesis) {
String text = hypothesis.getHypstr();
try {
Intent i= null;
if (text.equals(KEYPHRASE)) {
switchSearch(MENU_SEARCH);
}
if (text.equals(DIGITS_SEARCH)) {
//panggil class SMSReaderMain
recognizer.stop();
i = new Intent(getApplicationContext(),SMSReaderMain.class);
startActivity(i);
}
if (text.equals(FORECAST_SEARCH)) {
switchSearch(FORECAST_SEARCH);
}
//else
//((TextView) findViewById(R.id.result_text)).setText(text);
} catch (Exception e) {
e.printStackTrace();
}
}
//nge pop up keyword yang sesuai kita ucapin sama library yg udah ada
#Override
public void onResult(Hypothesis hypothesis) {
((TextView) findViewById(R.id.result_text)).setText("");
if (hypothesis != null) {
String text = hypothesis.getHypstr();
makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBeginningOfSpeech() {
}
//kembali ke menu utama
/*#Override
public void onEndOfSpeech() {
if (DIGITS_SEARCH.equals(recognizer.getSearchName())
|| FORECAST_SEARCH.equals(recognizer.getSearchName()))
switchSearch(KWS_SEARCH);
}**/
//nampilin caption yg di mau sesuai dengan keyword
public void switchSearch(String searchName) {
recognizer.stop();
recognizer.startListening(searchName);
String caption = getResources().getString(captions.get(searchName));
((TextView) findViewById(R.id.caption_text)).setText(caption);
}
//inisiasi recognizer di awal
public void setupRecognizer(File assetsDir) {
File modelsDir = new File(assetsDir, "models");
recognizer = defaultSetup()
.setAcousticModel(new File(modelsDir, "hmm/en-us-semi"))
.setDictionary(new File(modelsDir, "dict/cmu07a.dic"))
.setRawLogDir(assetsDir).setKeywordThreshold(1e-20f)
.getRecognizer();
recognizer.addListener(this);
// Create keyword-activation search.
recognizer.addKeyphraseSearch(KWS_SEARCH, KEYPHRASE);
// Create grammar-based searches.
File menuGrammar = new File(modelsDir, "grammar/mulai.gram");
recognizer.addGrammarSearch(MENU_SEARCH, menuGrammar);
//File digitsGrammar = new File(modelsDir, "grammar/digits.gram");
//recognizer.addGrammarSearch(DIGITS_SEARCH, digitsGrammar);
// Create language model search.
File languageModel = new File(modelsDir, "lm/weather.dmp");
recognizer.addNgramSearch(FORECAST_SEARCH, languageModel);
}
#Override
public void onEndOfSpeech() {
// TODO Auto-generated method stub
}
}
SMSReaderMAin.java
public class SMSReaderMain extends Activity {
private final int CHECK_CODE = 0x1;
private final int LONG_DURATION = 5000;
private final int SHORT_DURATION = 1200;
private Speaker speaker;
private ToggleButton toggle;
private OnCheckedChangeListener toggleListener;
private TextView smsText;
private TextView smsSender;
private BroadcastReceiver smsReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//PocketSphinxActivity ps = new PocketSphinxActivity();
//ps.setupRecognizer(null);
//ps.onPartialResult(null);
//ps.onResult(null);
//ps.switchSearch(null);
setContentView(R.layout.main_sms);
//recognizer.startListening(searchName);
toggle = (ToggleButton)findViewById(R.id.speechToggle);
smsText = (TextView)findViewById(R.id.sms_text);
smsSender = (TextView)findViewById(R.id.sms_sender);
toggleListener = new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton view, boolean isChecked) {
if(isChecked){
speaker.allow(true);
speaker.speak(getString(R.string.start_speaking));
}else{
speaker.speak(getString(R.string.stop_speaking));
speaker.allow(false);
}
}
};
toggle.setOnCheckedChangeListener(toggleListener);
checkTTS();
initializeSMSReceiver();
registerSMSReceiver();
}
private void checkTTS(){
Intent check = new Intent();
check.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(check, CHECK_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == CHECK_CODE){
if(resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS){
speaker = new Speaker(this);
}else {
Intent install = new Intent();
install.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(install);
}
}
}
private void initializeSMSReceiver(){
smsReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if(bundle!=null){
Object[] pdus = (Object[])bundle.get("pdus");
for(int i=0;i<pdus.length;i++){
byte[] pdu = (byte[])pdus[i];
SmsMessage message = SmsMessage.createFromPdu(pdu);
String text = message.getDisplayMessageBody();
String sender = getContactName(message.getOriginatingAddress());
speaker.pause(LONG_DURATION);
speaker.speak("You have a new message from" + sender + "!");
speaker.pause(SHORT_DURATION);
speaker.speak(text);
smsSender.setText("Message from " + sender);
smsText.setText(text);
}
}
}
};
}
private void registerSMSReceiver() {
IntentFilter intentFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(smsReceiver, intentFilter);
}
private String getContactName(String phone){
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));
String projection[] = new String[]{ContactsContract.Data.DISPLAY_NAME};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if(cursor.moveToFirst()){
return cursor.getString(0);
}else {
return "unknown number";
}
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(smsReceiver);
speaker.destroy();
}
}
This is a really wrong approach to the way of programming in Android. Activities are one of the main core components in an Android application that is managed directly by the OS, which means that the system creates them and are managed by the OS. The onCreate method is part of the lifecycle and it is automatically called by the system. Here you have the activity's lifecycle.
The way of starting a new activity is:
Intent intent = new Intent(mContext, MyActivity.class);
startActivity(intent);
As the activity is instanciated by the system, you cannot call directly to methods on it. The way of communicating between activities is by providing bundle objects in the intent, so in the new Activity you can get the data from:
getIntent().getExtras()
You can also provide backward information by using startActivityForResult instead of startActivity, receiving a result in onActivityResult.
You have the info you need here.
Activity corresponds to something you are going to display on screen. If you are not going to display anything, don't create activities.
In this example you do not need PocketsphinxActivity at all. You can move all the methods of PocketsphinxActivity into your SMSReaderMain activity.
If you want to separate speech recognition code into separate class you can create a separate PocketsphinxRecognizer class but inherit it from Object, not from the Activity.
I have created an app in which I have used SPenSdk libraries, My app is simple, What I do is on the start of the app I open a canvasView with a pen, eraser, undo and redo option.
I have two buttons, one save the canvas as an image in my SD card and another button is used to load the saved images.
Now my issue is, whenever I load the saved image and edit the saved images and again save the images, it is saved as new images instead of updating the saved images, why it happens?
I put my code here. Help me to solve this out, if possible with an example.
Code For java File
public class CanvasActivity extends Activity {
private CanvasView m_CanvasView;
private SettingView m_SettingView;
private Button m_PenButton, m_EraserButton, m_UndoButton, m_RedoButton, m_SaveButton;
private int mButtonTextNormalColor;
public static final String DEFAULT_APP_IMAGEDATA_DIRECTORY = "/mnt/sdcard/SmemoExample";
private File m_Folder = null;
public static final String SAVED_FILE_EXTENSION = "png";
public static final String EXTRA_IMAGE_PATH = "path";
public static final String EXTRA_IMAGE_NAME = "filename";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
m_PenButton = (Button) findViewById(R.id.pen_button);
m_PenButton.setOnClickListener(mBtnClickListener);
mButtonTextNormalColor = m_PenButton.getTextColors().getDefaultColor();
m_EraserButton = (Button) findViewById(R.id.erase_button);
m_EraserButton.setOnClickListener(mBtnClickListener);
m_UndoButton = (Button) findViewById(R.id.undo_button);
m_UndoButton.setOnClickListener(undoNredoBtnClickListener);
m_UndoButton.setEnabled(false);
m_RedoButton = (Button) findViewById(R.id.redo_button);
m_RedoButton.setOnClickListener(undoNredoBtnClickListener);
m_RedoButton.setEnabled(false);
m_SaveButton = (Button) findViewById(R.id.save_button);
m_SaveButton.setOnClickListener(mBtnClickListener);
m_CanvasView = (CanvasView) findViewById(R.id.canvas_view);
m_SettingView = (SettingView) findViewById(R.id.setting_view);
m_CanvasView.setSettingView(m_SettingView);
m_CanvasView.setOnHistoryChangeListener(historyChangeListener);
m_CanvasView.setInitializeFinishListener(mInitializeFinishListener);
m_Folder = new File(DEFAULT_APP_IMAGEDATA_DIRECTORY);
String mFileName = getIntent().getStringExtra(EXTRA_IMAGE_NAME);
loadCanvas(mFileName);
}
private OnClickListener undoNredoBtnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if (v == m_UndoButton) {
m_CanvasView.undo();
} else if (v == m_RedoButton) {
m_CanvasView.redo();
}
m_UndoButton.setEnabled(m_CanvasView.isUndoable());
m_RedoButton.setEnabled(m_CanvasView.isRedoable());
}
};
OnClickListener mBtnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == m_PenButton.getId()) {
m_CanvasView.changeModeTo(CanvasView.PEN_MODE);
m_PenButton.setSelected(true);
m_PenButton.setTextColor(Color.WHITE);
m_EraserButton.setSelected(false);
m_EraserButton.setTextColor(mButtonTextNormalColor);
if (m_PenButton.isSelected()) {
m_SettingView.showView(AbstractSettingView.PEN_SETTING_VIEW);
}
} else if (v.getId() == m_EraserButton.getId()) {
m_CanvasView.changeModeTo(CanvasView.ERASER_MODE);
m_EraserButton.setSelected(true);
m_EraserButton.setTextColor(Color.WHITE);
m_PenButton.setSelected(false);
m_PenButton.setTextColor(mButtonTextNormalColor);
if (m_EraserButton.isSelected()) {
m_SettingView.showView(AbstractSettingView.ERASER_SETTING_VIEW);
}
} else if(v.getId() == m_SaveButton.getId()) {
saveCanvas();
}
}
};
public boolean saveCanvas() {
byte[] buffer = m_CanvasView.getData();
if (buffer == null)
return false;
if (!(m_Folder.exists()))
m_Folder.mkdirs();
String savePath = m_Folder.getPath() + '/' + UtilitiesActivity.getUniqueFilename(m_Folder, "image", SAVED_FILE_EXTENSION);
if (UtilitiesActivity.writeBytedata(savePath, buffer))
return true;
else
return false;
}
public boolean loadCanvas(String fileName) {
String loadPath = m_Folder.getPath() + '/' + fileName;
byte[] buffer = UtilitiesActivity.readBytedata(loadPath);
if (buffer == null)
return false;
m_CanvasView.setData(buffer);
return true;
}
private CanvasView.OnHistoryChangeListener historyChangeListener = new CanvasView.OnHistoryChangeListener() {
#Override
public void onHistoryChanged(boolean bUndoable, boolean bRedoable) {
m_UndoButton.setEnabled(bUndoable);
m_RedoButton.setEnabled(bRedoable);
}
};
CanvasView.InitializeFinishListener mInitializeFinishListener = new CanvasView.InitializeFinishListener() {
#Override
public void onFinish() {
Bitmap bg = BitmapFactory.decodeResource(getResources(), R.drawable.canvas_bg);
m_CanvasView.setBackgroundImage(bg);
bg.recycle();
}
};
}
While you save an image, it takes a new name and save that. Old image wont be overwritten. So you can edit the save canvas function. The method shown below
public boolean saveCanvas()
{
byte[] buffer = mCanvasView.getData();
if(buffer == null)
return false;
String savePath = mFolder.getPath() + '/' + ExampleUtils.getUniqueFilename(mFolder, "image", SAVED_FILE_EXTENSION);
Log.d(TAG, "Save Path = " + savePath);
if(ExampleUtils.writeBytedata(savePath, buffer))
return true;
else
return false;
}
function "getUniqueFilename" generates a new name.So if you update an image, just avoid the function
ExampleUtils.getUniqueFilename(mFolder, "image", SAVED_FILE_EXTENSION);
and save with old name. Then it will be overwritten.
I want to retrieve token via Account Manager classes. Here is sample code that works for twitter but not for facebook plz help me.
public class AccountManagerActivity extends Activity {
AccountManager mAccountManager;
AccountManagerFuture<Bundle> c;
String token;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mAccountManager = AccountManager.get(this);
Account[] acc = mAccountManager.getAccounts();
for (int i = 1; i < acc.length; i++) {
System.out.println("Account name==" + acc[i].name);
System.out.println("Account Type==" + acc[i].type);
}
AuthenticatorDescription[] ad = mAccountManager.getAuthenticatorTypes();
for (int i = 1; i < ad.length; i++) {
System.out.println("AuthenticatorDescription==" + ad[i].type);
}
tokenForTwitter();
tokenForFacebook();
}
private void tokenForFacebook() {
Account[] accts = mAccountManager
.getAccountsByType("com.facebook.auth.login");
int i = 0;
if (accts.length > 0) {
System.out.println("here");
Account acct = accts[0];
c = mAccountManager.getAuthToken(acct,
"com.facebook.auth.token" , null,
this, new AccountManagerCallback<Bundle>() {
#Override
public void run(AccountManagerFuture<Bundle> arg0) {
try {
Bundle b = arg0.getResult();
System.out.println("Facebook THIS AUHTOKEN: "
+ b.getString(AccountManager.KEY_AUTHTOKEN));
Intent launch = (Intent) b
.get(AccountManager.KEY_INTENT);
if (launch != null) {
startActivityForResult(launch, 0);
return;
}
} catch (Exception e) {
System.out.println("EXCEPTION#AUTHTOKEN");
}
}
}, null);
c = mAccountManager.getAuthToken(acct,
"com.facebook.auth.token.secret" /*
* what goes here
*/, null, this,
new AccountManagerCallback<Bundle>() {
#Override
public void run(AccountManagerFuture<Bundle> arg0) {
try {
Bundle b = arg0.getResult();
System.out.println("Facebook THIS AUHTOKEN: "
+ b.getString(AccountManager.KEY_AUTHTOKEN));
Intent launch = (Intent) b
.get(AccountManager.KEY_INTENT);
if (launch != null) {
startActivityForResult(launch, 0);
return;
}
} catch (Exception e) {
System.out.println("EXCEPTION#AUTHTOKEN");
}
}
}, null);
// mHandler.sendMessageDelayed(mHandler.obtainMessage(CALL), 0);
i++;
}
}
public void tokenForTwitter() {
Account[] accts = mAccountManager
.getAccountsByType("com.twitter.android.auth.login");
int i = 0;
if (accts.length > 0) {
System.out.println("here");
Account acct = accts[0];
c = mAccountManager.getAuthToken(acct,
"com.twitter.android.oauth.token" /* what goes here */, null,
this, new AccountManagerCallback<Bundle>() {
#Override
public void run(AccountManagerFuture<Bundle> arg0) {
try {
Bundle b = arg0.getResult();
System.out.println("twitter THIS AUHTOKEN: "
+ b.getString(AccountManager.KEY_AUTHTOKEN));
Intent launch = (Intent) b
.get(AccountManager.KEY_INTENT);
if (launch != null) {
startActivityForResult(launch, 0);
return;
}
} catch (Exception e) {
System.out.println("EXCEPTION#AUTHTOKEN");
}
}
}, null);
c = mAccountManager.getAuthToken(acct,
"com.twitter.android.oauth.token.secret" /*
* what goes here
*/, null, this,
new AccountManagerCallback<Bundle>() {
#Override
public void run(AccountManagerFuture<Bundle> arg0) {
try {
Bundle b = arg0.getResult();
System.out.println("twitter THIS AUHTOKEN: "
+ b.getString(AccountManager.KEY_AUTHTOKEN));
Intent launch = (Intent) b
.get(AccountManager.KEY_INTENT);
if (launch != null) {
startActivityForResult(launch, 0);
return;
}
} catch (Exception e) {
System.out.println("EXCEPTION#AUTHTOKEN");
}
}
}, null);
// mHandler.sendMessageDelayed(mHandler.obtainMessage(CALL), 0);
i++;
}
}
}
Call AccountManager.getAccountsByType(null) to retrieve all accounts, and check the returned account data includes the information you need. It may simply not be exposed.
Try calling AccountManager.blockingGetAuthToken instead. Also, make sure your manifest has the USE_CREDENTIALS permission set correctly.
You can see this discussion How to retrieve an Facebook-AuthToken from the accounts saved on Android
But I would also suggest Facebook SDK with offline access permission(This permission makes the access token returned by the OAuth endpoint long-lived, otherwise auth token is valid only for 1 hour.)
You can also create intent and obtain token from facebook application
Intent intent = new Intent();
intent.setClassName("com.facebook.katana", "com.facebook.katana.ProxyAuth");
intent.putExtra("client_id", apiKey);
intent.putExtra("scope", scope);
try {
activity.startActivityForResult(intent, requestCode);
} catch (ActivityNotFoundException e) {
return false;
}
Then onActivityResult(int requestCode, int resultCode, Intent data) of you activity you can get the token using
data.getStringExtra("access_token");
Just for information, the facebook application part of getAuthToken is not implemented. When you decompile it, you see that it just returns null.
You should use the Facebook SDK.