sorry if this is a dummy question, but I am quite new coding in Android and using the Google Drive API.
In my app, I need to create a file within a folder I previously created. At the time that the folder is created, I can only retrieve the DriveID using DriveId.encodeToString. So, in order to get the ResourceID for the creation of the file in that folder, I have implemented the following code. Although the code is working, this code never returns to the previous activity.
Could anyone help me and explain the reason? I suspect that it should be something related to the .setResultCallback.
This is how I call the activity:
Intent intent = new Intent(this, test.class);
intent.putExtra("projectFolderID", selectedProject.getpId());
intent.putExtra("FileName", LIKED_FILE_NAME);
intent.putExtra("LikedArticle", userLikes);
//startActivityForResult(intent, LIKE_FILE);
startActivity(intent);
This is the code in the activity to create the file
public class test extends BaseActivity {
private DriveId mFolderDriveId;
private DriveId projectFolderID;
private String folderResourceID;
private DriveFolder appFolder;
private String nFile;
private LikedArticles userLikes;
private boolean printed = false;
#Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
//Get Data from previous activity
Intent intentDisplayQuery = getIntent();
projectFolderID = DriveId.decodeFromString(intentDisplayQuery.getStringExtra("projectFolderID"));
nFile = intentDisplayQuery.getStringExtra("FileName");
userLikes = (LikedArticles) intentDisplayQuery.getSerializableExtra("LikedArticle");
//Retrieve the resourceId of the project folder from decoding Id
if (userLikes.getmLikedArticle().size()>0){
appFolder = projectFolderID.asDriveFolder();
appFolder.getMetadata(getGoogleApiClient())
.setResultCallback(metadataCallback);
}
}
final private ResultCallback<DriveResource.MetadataResult> metadataCallback = new
ResultCallback<DriveResource.MetadataResult>() {
#Override
public void onResult(DriveResource.MetadataResult metadataResult) {
if (!metadataResult.getStatus().isSuccess()) {
showMessage("Problem while retrieving files");
return;
}
Metadata mdb;
try {
mdb = metadataResult.getMetadata();
mFolderDriveId = mdb.getDriveId();
folderResourceID = mFolderDriveId.getResourceId();
/*Drive.DriveApi.fetchDriveId(getGoogleApiClient(), folderResourceID)
.setResultCallback(idCallback);*/
} finally { }
}
};
}
Thanks in advance for your help.
Related
I am trying to set up android app link for my app. The problem is that the intent is received by an activity and I need to send this event to my javascript code(to navigate to the correct screen) through RCTDeviceEventEmitter but for this to happen I need to get react context somehow in my activity's code...I have no idea how to do this..This is what I have tried:
public class NewFriendActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(null);
class ReactContextFetcher extends ReactContextBaseJavaModule {
#Override
public String getName() {
return "ReactContextFetcher";
}
public ReactContext fetchReactContext() {
return getReactApplicationContext();
}
}
Intent intent = getIntent();
String data = intent.getData().toString();
String user = data.split("/add-friend/")[1];
Log.d("obscure_tag", user);
ReactContext rContext = new ReactContextFetcher().fetchReactContext();
Log.d("obscure_tag", "this is run as well..");
sendEvent(rContext, "NewFriend", user);
}
private void sendEvent(ReactContext reactContext,
String eventName, String user) {
reactContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(eventName, user);
}
}
"user" gets logged but "this is run as well.." doesn't, the app crashes before that..So I get that fetchReactContext() is not the correct way to get react context..I referred to this but actually I did not understand what that guy is trying to say..How should I get react context in this situation?
I have an audio app with the home Activity containing a list of items. The user selects an item and I pass an ID to another Activity which has the controls (play/pause/volume, etc). The audio playback is handed in a MediaBrowserService. I need to detect if the item the user selects is currently playing but I can't figure out how outside of saving the ID in local storage (SharedPrefs or SQlite).
I pass the ID of the item from the second Activity to the MediaBrowserService though a Bundle. I thought I could then retrieve the ID in the second Activity using getExtras() but it always returns 0 or null, depending on which code I use (see below).
I'm not opposed to using local storage but seem like there should be a better way. This is what I have so far:
public class EpisodeActivity extends Activity {
private MediaBrowserCompat mMediaBrowserCompat;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Bundle extras = new Bundle();
extras.putInt("episodeid", getIntent().getExtras().getInt("episodeid")); //passed in from Home Activity
mMediaBrowserCompat = new MediaBrowserCompat(
this,
new ComponentName(this, MediaPlayerService.class),
mMediaBrowserCompatConnectionCallback,
extras
);
mPlayButton.setOnClickListener(view -> {
final Bundle extras = new Bundle();
extras.putInt("episodeid", getIntent().getExtras().getInt("episodeid")); //passed in from Home Activity
String url = "http://www.example.com/media.mp3"
MediaControllerCompat.getMediaController(mActivity).getTransportControls().playFromUri(Uri.parse(uri), extras);
});
if (MediaControllerCompat.getMediaController(mActivity).getPlaybackState() != null &&
MediaControllerCompat.getMediaController(mActivity).getPlaybackState().getState() == PlaybackStateCompat.STATE_PLAYING) {
int episodeID = mMediaBrowserCompat.getExtras().getInt("episodeid"); //always returns 0
//also tried this but getExtras is null
int episodeID = MediaControllerCompat.getMediaController(mActivity).getExtras().getInt("episodeid");
}
}
}
public class MediaPlayerService extends MediaBrowserServiceCompat {
private MediaSessionCompat mMediaSessionCompat;
#Override
public void onCreate() {
super.onCreate();
final ComponentName mediaButtonReceiver = new ComponentName(getApplicationContext(), MediaButtonReceiver.class);
mMediaSessionCompat = new MediaSessionCompat(getApplicationContext(), getString(R.string.app_name), mediaButtonReceiver, null);
mMediaSessionCompat.setCallback(mMediaSessionCallback);
...
}
private MediaSessionCompat.Callback mMediaSessionCallback = new MediaSessionCompat.Callback() {
#Override
public void onPlayFromUri(final Uri uri, final Bundle extras) {
super.onPlayFromUri(uri, extras);
int episodeId = extras.getInt("episodeid");
String url = GetUrl(episodeId);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(uri);
mMediaPlayer.prepareAsync();
...
}
}
}
media_controller.getMetadata().getDescription().getMediaId() may be what you're looking for. If not, maybe try using MediaMetadataCompat.Builder() to set some metadata to each of your episodes
MediaMetadataCompat.Builder().putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, episodeID).build()
something like that, I don't think you need to use the METADATA_KEYs either, you can probably replace that with "episode id" or whatever string you want to use as a key.
edit: if you go the metadata route, you may want to use that to build mediaitems.
MediaMetadataCompat episode_meta = new MediaMetadataCompat.Builder()
.putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, episodeID)
.build();
episode_mediaitem = new MediaBrowserCompat.MediaItem(episode_meta.getDescription(), MediaBrowserCompat.MediaItem.FLAG_PLAYABLE));
Hope i helped
edit: using the media items enables you to use the media_controller.getMetadata().getDescription().getMediaId() from above, I think
mPlayButton.setOnClickListener(view -> {
final Bundle extras = new Bundle();
extras.putInt("episodeid", getIntent().getExtras().getInt("episodeid")); //passed in from Home Activity
String url = "http://www.example.com/media.mp3"
MediaControllerCompat.getMediaController(mActivity).getTransportControls().playFromUri(Uri.parse(uri), extras);
});
here you should put url instead uri when you parse Uri.
I´m pretty new in android. I have made communication between two Apps with BroadcastReceiver and intentServices .
The thing is, I want to send information to the app2 from app1. In app1 I need to access a variable which is in MainActivity.class , I need to send it to servicev.class (the service where the intent is handled) but the variable "res" is null when I access it, why does that happen? (App2 calls app1 onHandleIntent and it breaks in res.getOtp() ) I try to create an extra setter getter class and also an intent but getIntent() does not work inside onHandleIntent... how can I achieve to pass res.getOTP (string) ? I really dont want to use SQLite
servicev:
public class servicev extends IntentService {
private static final int RESULT_OK = 1;
protected ResultReceiver mReceiver;
public servicev() {
super("yeah");
}
#Override
protected void onHandleIntent(Intent intent) {
//I receive here the intent from app2 and I need to response with res.getOTP()
helper h = new helper();
String val = intent.getStringExtra("foo");
Intent in = new Intent("com.banorte.bem.movil.veriToken.SendBroadcast");
in.putExtra("resultCode", this.RESULT_OK);
in.putExtra("resultValue", "My Result Value. Passed in: " + h.getRes().getOtp()); //h here is null... setter and getter approach does not work... maybe sqlite could work but it is necesary?
sendBroadcast(in);
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
VTTokenAPI api;
TextView textView;
Button button;
EditText input;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidSetup.getInstance().init(this);
helper h = new helper();
api = new VTTokenAPI("FFFFFF");
res = api.getStatus();
res.getOtp(); //correct value
h.setRes(res);
setContentView(R.layout.activity_main);
}
}
helper:
public class helper {
public VTResult getRes() {
return res;
}
public void setRes(VTResult res) {
this.res = res;
}
VTResult res;
}
You are trying to instantiate a new MainActivity which is not the same as the running activity but a new instance.
If you need your IntentService to be able to get data from a running Activity you have options such as using SharedPreferences or SQLite. Instead of keeping the data in memory try to persist it in some database in the onCreate and then try to read it from the storage during handleIntent
public void doSomething(View view) {
String url, link_url, pro;
url = textIn.getText().toString();
pro = spin.getSelectedItem().toString();
c1 = new ConnectInternetClass(this);
if (!url.isEmpty()) {
if (url.contains(".") && !(url.contains(" "))) {
if (url.split("\\.").length > 1) {
if (checkConnection()) {
link_url = pro+url;
c1.execute(link_url);
} else {
Toast.makeText(this, "check your internet connection", Toast.LENGTH_SHORT).show();
myText.setText("No Internet Connection");
}
} else {
myText.setText("Unknown domain");
}
} else {
myText.setText("Invalid URL");
}
} else {
myText.setText("URL can\'t empty");
}
}
I have that code to show a web page source. I want to show the result in another activity, but I don't know how. I use the create object from the first activity, but it's not method
public class ShowActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show);
MainActivity ma = new MainActivity();
}
Passing data from a activity , linkUrl is your variable which data you want to pass :
Intent intent = new Intent (YourActivity.this, ShowActivity.class) ;
intent.putExtra("KEY_LINK" , linkUrl);
startActivity(intent);
Receiving data from ShowActivity , Access the data by the key in onCreate():
String url = getIntent().getStringExtra("KEY_LINK");
Link : How do I pass data between Activities in Android application?
Link : https://developer.android.com/training/basics/firstapp/starting-activity.html
Why you use this kind of things. If you want to load a web page in an activity use webview for it. no need two activities to do that. Another way you can create a class which has your doSomething method (it should be public static) and call it from an activity by using that's class object. When you coding don't create unnecessary activities.
I am trying to send information from my main activity class to another class in my app package. The information is used to update an AlertDialog automatically. Here is the code I've been working with:
//This is in MainActivity.class
//Tests to see if SyncDialog will update itself with new intents.
public void testLoop() {
int n = 0;
Intent intent = new Intent(this, SyncDialog.class);
while (n != 10) {
intent.putExtra(TEST_NUMBER, n);
n++;
}
}
//This is in SyncDialog.class
//This method should get the int value from MainActivity
protected void onNewIntent(Intent intent) {
int n = intent.getIntExtra(TEST_NUMBER, 0);
showNextDialog(n);
}
TEST_NUMBER is defined as a public constant at the top of MainActivity, and I even tried importing MainActivity into SyncDialog.class.
Is there any way to fix this?
You will have to make it a static constant if you want to access it in the way you are attempting. In MainActivity:
public static String TEST_NUMBER = "test";
and in SyncDialog:
intent.getExtra(MainActivity.TEST_NUMBER, 0)