Been a lurker on this site to help find answers to some of my problems before, but I am currently stuck on this and could not find a recent solution. The closest answers I found to my problem were Yelp API Android Integration and Yelp Integration in Android
I tried following the steps in the 2nd link but they are a bit outdated. I have registered for an API, downloaded the jar files from the github and synced them, and made the YelpAPI.java and TwoStepOAuth.java files and removed the main method from YelpAPI. I am stuck on step 4 on the search part. I tried to call the queryAPI method from inside an onClick method I made for a button
public void getRandom(View view) {
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
YelpAPI.YelpAPICLI yelpApiCli = new YelpAPI.YelpAPICLI();
new JCommander(yelpApiCli);
YelpAPI yelpApi = new YelpAPI(CONSUMER_KEY, CONSUMER_SECRET, TOKEN, TOKEN_SECRET);
try {
YelpAPI.queryAPI(yelpApi, yelpApiCli);
} catch (JSONException e) {
e.printStackTrace();
}
}
Basically what I want this to do is, when the button is pressed, I want it to go to a second screen that will display what I query Yelp for. I haven't worked on that part yet, right now I just want to get a result back from Yelp. Keep in mind I am a complete noob at Android Studio and at most intermediate at Java.
Any help is greatly appreciated, it seems like its a really simple problem but its taking me forever to figure out on my own.
You can't do blocking task like downloading or image loading in android's Main thread (UI Thread). You can't block UI for more than 5 seconds. If you try it to block for more than 5 seconds than your app will stop working and display "Unfornutaley your app has stopped working" because of error too much work on main thread. So you need to make use of async task.
Related
My Android app features a text input box that has a button on the right of the EditText to call the voice-input feature.
I am porting the app with Codename One. At present time the iOS port is the goal.
The button has a suitable icon. This is the code:
voiceInputButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent voiceIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
try {
activity.startActivityForResult(voiceIntent, RESULT_SPEECH_REQUEST_CODE);
} catch (ActivityNotFoundException ex) {
}
}
});
It works very well, the voice-input screen is called and then the result is passed back to the app as a string.
The string is what the user said (for example, a single word).
I need to have this functionality in the CodenameOne app for iOS.
What should be the equivalent? Is it necessary to call native iOS functions, through the native interface?
You can implement speech-to-text via Speech framework, to perform speech recognition on live or prerecorded audio. More info: https://developer.apple.com/documentation/speech
About Codename One, you can create a native interface using Objective-C code.
To use the Speech framework with Objective-C, see this answer:
https://stackoverflow.com/a/43834120
The answer says so: «[...] To get this running and test it you just need a very basic UI, just create an UIButton and assign the microPhoneTapped action to it, when pressed the app should start listening and logging everything that it hears through the microphone to the console (in the sample code NSLog is the only thing receiving the text). It should stop the recording when pressed again. [...]». This seems very close to what you asked.
Obviously the creation of the native interface takes time. For further help, you can ask more specific questions, I hope I have given you a useful indication.
Lastly, there are also alternative solutions, again in Objective-C, such as: https://github.com/Azure-Samples/cognitive-services-speech-sdk/tree/master/quickstart/objectivec/ios/from-microphone
You can search on the web for: objective-c speech-to-text
I have a Unity Scene built with Cardboard SDK and exported as a library for Android. The library is used to play videos in cardboard mode on the android app. it's not the whole app, but a part in it. The rest of the android app is built with Kotlin and Java.
I have implemented that and all the functions work as expected, but, exiting the scene crashes the android.
We tried various ways to clear player prefs and even clear memory before closing the scene. But on android it always crashes. I have two android phones with android 9 and 10 for testing.
In the android app, I have made it such that as soon as the app crashes, I try to recover. My crash is that some lateinit var variables are destroyed. Their value becomes null and recovering the previous activity crashes it. So right after I exit the unity scene, I load the dereferenced variables back into memory and everything works again.
Note: I have tried using Application.Quit(); in unity, but it just closes the whole app. On the other hand, I only want to close the running scene
In unity [I call a function goBack in android part to close the app]:
public void GoToHome()
{
Pause();
Stop();
Resources.UnloadUnusedAssets();
PlayerPrefs.DeleteAll();
AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
jo.Call("goBack");
}
In App:
public void goBack()
{
UnityPlayer.currentActivity.finish();
finish();
loadDerereferencedVars();
}
This goes perfectly on android 9. On the other phone with android 10, after I close the scene, the app continues to function, but, there comes a message
When I click close app, the app continues to work.
I have checked the logs and there is a null pointer dereference cause for the crash in Unity Main >...
If you'd like to see the Unity Crash Log from LogCat in Android Studio
So, since the app is still running, I thought, it would be better to just hide the crash report and just let the user not know about this crash, but still report it.
I tried enclosing my app in Application and added a method to catch uncaughtException.
here is my application class:
public class MyApp extends Application {
private static final String TAG = "MyAPP";
#Override
public void onCreate() {
super.onCreate();
Thread.setDefaultUncaughtExceptionHandler(
new Thread.UncaughtExceptionHandler() {
#Override
public void uncaughtException (Thread thread, Throwable e) {
handleUncaughtException (thread, e);
}
});
}
/**
* Handles Uncaught Exceptions
*/
private void handleUncaughtException (Thread thread, Throwable e) {
// The following shows what I'd like, though it won't work like this.
Toast.makeText(getApplicationContext(), "Looks like I am having a bad day!", Toast.LENGTH_LONG).show();
Log.e("UncaughtException", "I found an exception!");
// Add some code logic if needed based on your requirement
}
}
Again, this works perfectly in Android 9 and I also got the error reported. However in the phone with android 10, I just get the crash report like the image above and no error is reported.
I want to know why the crash handling is not working and how can I fix it?
I would not finish the Activity you came from, instead just open a new intent (on UnityActivity). When you end this intent the app will come back to the last active Activity.
I will give you my script as an example:
public void sendJobToUnity(String fileName, boolean isNewJob){
//creates a new job. It exists inside the JobSelector Activity
isUnityLoaded = true;
//this is what you are looking for part1
Intent i = new Intent(JobSelector.this, MainUnityActivity.class); //same as (CurrentActivity.this, UnityActivity.this)
//those are how I send some data across the app. just ignore it
//i.putExtra("jobName", fileName);
//i.putExtra("isNewJob",isNewJob);
//i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivityForResult(i, 1); //this is what you are looking for part2
}
For closing it, in the MainUnityActivity Activity I have an override that Unity sends to Android in order to Unload the activity (not quit it completely cause you cannot load it again if you do it) like this:
#Override
protected void receiveJobAndUnloadUnity(String data){
saveCurrentJob(data); //saves the job it receives from Unity
mUnityPlayer.unload(); //this is what you are looking for part3
}
If you want to unload Unity from android you can put "mUnityPlayer.unload();" wherever you want, provided you have started the Activity the way I've shown you.
Note that "mUnityPlayer" is a default Unity variable and cannot be renamed
I have some new questions in today's citymaps development.
In the Android studio,if I develop the code for citymap, there are always no logs showing but for others that does not happen. Why?
According to the citymaps official website, to create a map instance with CitymapsMapFragment, but in the sample project which citymaps provides, it uses SupportCitymapsMpaFragment ,What is the difference between them?
When the map is loading complete, is it automatically positioning to the current position or some other default position? Where is it?
If I open the GPS location,I can locate to the current position and show a blue arrow quickly, but too much power consumption,are there any other location way like network or base station location?
Code follows:
CitymapsMapFragment fragment = (CitymapsMapFragment)fragmentManager.findFragmentById(R.id.map);
if (fragment != null) {
fragment.setMapViewListener(this);
}
I did not find the fragment have the method setMapViewListener but setMapViewReadyListener,does it right?
Other code:
CitymapsMapView mapView = new CitymapsMapView(this, options, this);
When I add animate in additional methods like this:
mapView.setMapPosition(position, 300, new MapViewAnimationListener() {
#Override
public void onAnimationEnd(boolean completed) {
Log.d("SomeApp", "Move Complete!");
}
});
the project fails and exits,I tried to surround the code with try-catch block to catch exception for purpose, but nothing shows in logcat view. Why?
I am developer on the Citymaps project. I will do my best to answer all your questions
1) If you are not receiving log statements, this is likely an issue with your own application, IDE, or device configuration. In our own application, which uses the Citymaps SDK, we have no issues with logging.
2) Prior to using the Citymaps SDK, it is highly advisable that you familiarize yourself with fragments, but the short version is that SupportCitymapsMapFragment extends from the Fragment class in the v4 support library.
3) It is up to you to set the default position the map.
4) If you create a class which implements from the LocationSource interface, and then call mapView.setLocationSource, you can modify the behaviors of the map's location services. For an example, have a look at CitymapsLocationSource.java, which is the default implementation for this interface used by the SDK.
As for the exception you are having, you have not provided nearly enough information. Please show a stack trace, and I may be able to help.
Thank you for using our SDK, feel free to post again with any more questions.
I'm making tetris in Android via eclipse (I use an emulator of eclipse). The program worked untill I added a bunch of stuff (maybe wasn't so smart, but nothing visual was changed so) I didn't run the progam in a while. Now I can go to my first activity, but as soon as I click the button to go to my next one, the program stops working :(
Here is my code:
MainActivity.java http://pastebin.com/P9AAJ90n (button towards Tetris.java)
Tetris.java http://pastebin.com/WEsXshPh (probably contains error)
TetrisView.java http://pastebin.com/ejUJjLMk
I think that's the code the problem is located in, but do ask for more if required...
(I think the problem is located in the onCreate() method of Tetris.java
Now the LogCat Debug text:
http://pastebin.com/MSCxHdsr
Thanks in advance
PS: If I remove the whole onCreate() of Tetris.java except the first 2 lines, I can run the program.
-----------------------------------------------EDIT-----------------------------------------------
I removed one of the setContentView(), still stops working. Also looked into DroppedTiles, thought I fixed it but didn't :(
Logcat: http://pastebin.com/JHu7n1uA
DroppedTiles: http://pastebin.com/tyKLuxVd
Block: http://pastebin.com/zmPa7cv7
I commented the DroppedTiles in Tetris.java...
Tried reading the debug log but most of it I do not understand sadly
you're setting content view twice
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tetris);
// Intent intent = getIntent();
// Add mTetrisView to this
mTetrisView = new TetrisView(this, null);
setContentView(mTetrisView);
mTetrisView.init();
figure out which is the correct one (probably the first) and remove the other.
I am a newbie in Android and creating a mini FTP download manager for myself.. I am using multithreading, each thread to handle one download or upload. In the MainActivity.java, I am using two spinners in the view. One to list the files on the server (which can be downloaded), another to list files on my phone folder (which can be uploaded). I want to update the first (download) spinner when a new file is uploaded, and the second (upload) spinner when a new file is downloaded. However I am not able to make out how to update the spinners only when the corresponding threads finish their job. I created methods to update the spinners in the MainActivity.java and tried to call them in the end of the run() of the threads, so that they'l be updated once the threads finish downloading/uploading. However, I am getting an error in LogCat saying
android.view.ViewRoot$CalledFromWrongThreadException : Only the original thread that created a view hierarchy can touch its views.
The method for updating upload spinner is:
void upScrollUpdate() {
spinup=(Spinner)findViewById(R.id.uploadspin);
spinup.setEnabled(false);
String[] upload={"No Files"};
File sdDir=Environment.getExternalStorageDirectory();
File dir=new File (sdDir.getAbsolutePath() + "/aFTP");
File[] fArray=dir.listFiles();
if(fArray.length>0) {
upload=new String[fArray.length];
}
for(int i=0;i<fArray.length;i++) {
upload[i]=fArray[i].getName();
}
ArrayAdapter<String> saaUpload=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,upload);
spinup.setAdapter(saaUpload);
if(spinup.getSelectedItem().toString().equalsIgnoreCase("No Files")) {
uploadButton.setEnabled(false);
}
spinup.setEnabled(true);
}
Why cant this method be called from another thread, and what is the other way out of this, I simply want to update the spinners but I have spent a whole day on this only thing...
For any piece of code that will update the UI, put that in this block:
Refer to this link for more info on runOnUiThread
runOnUiThread(new Runnable() {
public void run() {
// RUN THE CODE WHICH IS GIVING THAT EXCEPTION HERE
}
});
The same can also be done like this:
Runnable run = new Runnable() {
#Override
public void run() {
// RUN THE CODE WHICH IS GIVING THAT EXCEPTION HERE
}
}; YourActivity.this.runOnUiThread(run);
Alternatively, you can make use of an AsyncTask. You can do your processing in the doInBackground() method and then update the Spinners in the onPostExecute() method of the AsyncTask
EDIT: Check these tutorials to help you get started with using AsyncTask:
http://www.vogella.com/articles/AndroidPerformance/article.html#asynctask
http://androidresearch.wordpress.com/2012/03/17/understanding-asynctask-once-and-forever/
http://android10.org/index.php/articlesother/239-android-application-and-asynctask-basics
http://mobileorchard.com/android-app-developmentthreading-part-2-async-tasks/
http://thenewboston.org/watch.php?cat=6&number=101
The 5th link to thenewboston.org has about 200 odd video tutorials on YouTube here: http://www.youtube.com/course?list=EC2F07DBCDCC01493A&feature=plcp
EDIT 2: Check the edit in this link here: https://stackoverflow.com/a/13265776/450534
It is at the bottom of the answer.
Anything to do with views should be done on UI thread.
You can use activityInstance.runOnUIThread() to handle this scenario of updating views from different thread.
Refer: Android: RunOnUiThread vs AsyncTask