Problem in Finding Resource File in Android - android-layout

Hi i am using Google Maps in a code
This is the code written in the activity file
package com.hellomaps;
import android.app.Activity;
import android.os.Bundle;
import com.google.android.maps.MapActivity;
public class HelloGoogleMaps extends MapActivity{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
}
Now in the line setContentView(R.layout.main) it does not recognse "R" and hence mapview cannot be used in the activity as it doesnot recognse the view
I know android.R and com.google.R should not be imported.
i am stuck here .. kindly help..!!
Thanks in Advance

R file is generated when you compile your project. So if you are using eclipse just press ctrl+b and R file should appear in gen folder in your project.
If you checked out project from SVN or some other version control you could have problem with R file. If you do, create new android project in eclipse then copy/paste source and resources from checked out project to new created one and build. Hope this helps.

Related

How to move from activity 2 to activity 3 in android studio

I've created three activities. My first MainActivity has two buttons, one that takes you to Activity2 and one that takes you to Activity3. Both of those buttons work, I've managed to code them correctly.
But then on Activity3 there's a button that's supposed to take you also to Activity2, and it's not working. I've tried several things but I can't seem to figure it out. Is it possible to code several buttons that lead to the same activity? If so please help cause I'm new at coding and stuff. Also here's how I've been coding the buttons :
1-after creating the activity, I go to the Java file and create a new class. In that class I write the following code :
class className : AppCompatActivity(){
override fun onCreate (savedInstance : Bundle?){
super.onCreate(savedInstance)
setContentView(R.layout.activity2)
}
}
Then I add it to the manifest
2-then I go back to the MainActivity and write this :
val anyName = buttonName
anyName.setOnClickListener {
startActivity(Intent(this, class Name :: class.java))
}
Of course android studio takes care of everything and imports everything that's needed but the second I add more than two of those in my MainActivity the whole app crashes.
Please explain this as simply as possible as, again, I'm really new to coding and android studio.
Thank you !
To go back on an activity you can just use finish() on any function, but if you want to take any information with you, you should look for more information about startActivityforResult().
However next time upload the code and not this pseudocode please, it would help a lot!
When you creating a new activity, you need also to add to it the new XML file, which will be display UI in the Activity page.
You can do it in two ways:
1. Custom.
Create a new ClassName.kt (Java.class in Java) and attach inside onCreate() method a XML layout, which will displaying all views in Activity page.
2. With Android Studio.
Just right-click in your package name folder, where appears your, for example, empty activity when you start new an Android Studio Project. Then select new, then in bottom side of drop-downed view select type of new activity what you want. For example, it is Empty Activity. So, lets sum above information: right-click at your package name folder -> new -> type of activity.
For what below info? I see in your example code, which you show as code in Activity number 3, what you have in onCreate() this line of code setContentView(R.layout.activity2). It is line means, what you add XML file into your activity. One XML file for activity can be used only for one activity if you want to show, after click on button another activity. Rather you will see only one screen because two activities use one layout. So, check your activities
need to be something like this:
1.In ActivityOne.
class ActivityOne : Activity() {
override fun onCreate (savedInstance : Bundle?) {
super.onCreate(savedInstance)
setContentView(R.layout.activity1)
}
}
1.In ActivityTwo.
class ActivityOne : Activity() {
override fun onCreate (savedInstance : Bundle?) {
super.onCreate(savedInstance)
setContentView(R.layout.activity2)
}
}
1.In ActivityThree.
class ActivityThree : Activity() {
override fun onCreate (savedInstance : Bundle?) {
super.onCreate(savedInstance)
setContentView(R.layout.activity3)
}
}
Make sure if you want to create a new activity First right click app then goto new -> Activity -> Empty Activity .
finally you can add onClick in your Button tag , then use startActivity method.
public void methodName(View view) {
startActivity(new Intent(this,ActivityName.class));
}
Example Code:
MainActivity.java:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void gotoTwo(View view) {
startActivity(new Intent(this,Activity2.class));
}
public void gotoThree(View view) {
startActivity(new Intent(this,Activity3.class));
}
}
activity_main.xml :
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="200dp"
android:layout_marginRight="240dp"
android:onClick="gotoTwo"
android:text="Activity2" />
Don`t forgot to create a new java you should create a new xml file too

Android Studio 3.2.1: Silent Mode Toggle app crashes when clicked even though no error in code

I'm just starting to learn coding for Android App by following the book Android App Development for Dummies to create the Silent Mode Toggle App.
Everything seems fine in the code (no error except for warning that:
"Casting 'findViewById(R.id.phone_icon)' to 'ImageView' is redundant.
This inspection reports unnecessary cast expressions."
I have read through a similar problem here (Application Crashes - Silent Mode Toggle - Android for Dummies) and it says to try:
1) Change "extends ActionBarActivity" to just "extends Activity" and import - mine is already as such.
2) delete or comment the 'if' in the onCreate method out - mine don't have this section.
3) change the parameter of the setContentView to: R.layout.fragment_main - not very sure what this means but don't seem to be relevant to my code? (his codes and mine are slightly different)
MainActivity.java Code
package com.dummies.silentmodetoggle;
import android.app.Activity;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import com.dummies.silentmodetoggle.util.RingerHelper;
public class MainActivity extends Activity {
AudioManager audioManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
setContentView(R.layout.activity_main);
FrameLayout contentView =
(FrameLayout) findViewById(R.id.content);
contentView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
RingerHelper.performToggle(audioManager);
updateUi();
}
});
}
private void updateUi() {
ImageView imageView = (ImageView) findViewById(R.id.phone_icon);
int phoneImage = RingerHelper.isPhoneSilent(audioManager)
? R.mipmap.ringer_off
: R.mipmap.ringer_on;
imageView.setImageResource(phoneImage);
}
#Override
protected void onResume(){
super.onResume();
// Update our UI in case anything has changed.
updateUi();
}
}
RingerHelper.java
The book says to create a java file at: "src/main/java/com/dummies/silentmodetoggle/util/RingerHelper.java" but did not state how. Since I do not have a util folder so I'd created a package (New>Package) at "src/main/java/com.dummies.silentmodetoggle" and added the RingerHelper java file in the util folder. Note sure if this is the problem? The code is as below:
package com.dummies.silentmodetoggle.util;
import android.media.AudioManager;
public class RingerHelper {
// private to prevent users from creating a RingerHelper object
private RingerHelper(){}
/* Toggles the phone's silent mode */
public static void performToggle(AudioManager audioManager) {
// If the phone is currently silent, then unsilence it. If
// it's currently normal, then silence it.
audioManager.setRingerMode(
isPhoneSilent(audioManager)
? AudioManager.RINGER_MODE_NORMAL
: AudioManager.RINGER_MODE_SILENT);
}
/* Returns whether the phone is currently in silent mode. */
public static boolean isPhoneSilent(AudioManager audioManager){
return audioManager.getRingerMode()
== AudioManager.RINGER_MODE_SILENT;
}
}
Error from LogCat when I clicked the button on app
2018-12-01 22:11:44.029 30122-30122/com.dummies.silentmodetoggle E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.dummies.silentmodetoggle, PID: 30122
java.lang.SecurityException: Not allowed to change Do Not Disturb state
at android.os.Parcel.readException(Parcel.java:1683)
at android.os.Parcel.readException(Parcel.java:1636)
at android.media.IAudioService$Stub$Proxy.setRingerModeExternal(IAudioService.java:962)
at android.media.AudioManager.setRingerMode(AudioManager.java:1022)
at com.dummies.silentmodetoggle.util.RingerHelper.performToggle(RingerHelper.java:13)
at com.dummies.silentmodetoggle.MainActivity$1.onClick(MainActivity.java:60)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
2018-12-01 22:11:44.672 1315-1315/? E/EGL_emulation: tid 1315: eglCreateSyncKHR(1901): error 0x3004 (EGL_BAD_ATTRIBUTE)
Otherwise the app seems to work fine, ie, when I click on the volume button of the device itself to silent, the app image will change to silent and vice versa. It just crashes when I try to click on the image of the app itself.
I really have no idea what's going on. Please help. Thanks very much!
You need to add permissions for Do Not Disturb State. I was facing the same issue and I added the following lines to my Main_Activity.java code in onCreate method and it works fine Now:
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if(notificationManager.isNotificationPolicyAccessGranted())
{
Intent intent = new Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
startActivity(intent);
}

TarsosDSP in Android Studio

This is my first post on SO and I am trying to combine my music skills with computer science.
I am using Android studio 3.1.2 with gradle 4.5, Nexus 5X, API 25, Android 7.1.1, Windows 7.
I followed very careful these instructions:
Create a project called Pitchbender
Download the .jar of TarsosDSP and included in
C:\Users\Carlos\AndroidStudioProjects\Pitchbender\app\libs\TarsosDSP-Android-latest
I checked the build.gradle of my project:
dependencies { implementation fileTree(dir: ‘libs’, include: [‘*.jar’]) }
In my project, I have the following imports automatically done by Android Studio:
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import be.tarsos.dsp.AudioEvent
import be.tarsos.dsp.io.android.AudioDispatcherFactory
import be.tarsos.dsp.pitch.PitchDetectionHandler
import be.tarsos.dsp.pitch.PitchDetectionResult
import be.tarsos.dsp.pitch.PitchProcessor
import kotlinx.android.synthetic.main.activity_main.*
import be.tarsos.dsp.pitch.PitchProcessor.PitchEstimationAlgorithm
import be.tarsos.dsp.AudioProcessor
import android.widget.TextView
import be.tarsos.dsp.AudioDispatcher
I have this permission in my manifest file
uses-permission android:name=”android.permission.RECORD_AUDIO”
Android Studio gives the option to convert to Kotlin the first line of the following code:
AudioDispatcher dispatcher = AudioDispatcherFactory.fromDefaultMicrophone(22050,1024,0);
If I respond to “No” to the Kotlin conversion, I have the following compilation error:
Clasifier “AudioDispatcher” does not have any companion object, and thus must be initialized here.
What can I do?
If I respond “Yes” to the Kotlin conversion question, that statement is converted to
val dispatcher = AudioDispatcherFactory.fromDefaultMicrophone(22050, 1024, 0)
and then, when I run this program, Android informs me that there is an error and closes my project and keeps closing my project. What to do?
Please help to run at least that first instruction of the complete code:
PitchDetectionHandler pdh = new PitchDetectionHandler() {
#Override
public void handlePitch(PitchDetectionResult res, AudioEvent e){
final float pitchInHz = res.getPitch();
runOnUiThread(new Runnable() {
#Override
public void run() {
processPitch(pitchInHz);
}
});
}
};
AudioProcessor pitchProcessor = new PitchProcessor(PitchEstimationAlgorithm.FFT_YIN, 22050, 1024, pdh);
dispatcher.addAudioProcessor(pitchProcessor);
Thread audioThread = new Thread(dispatcher, "Audio Thread");
audioThread.start();
Question:
Do you have any simple project in Android Studio, so that I can see what my errors are?
I had a similar problem when I tried to run this example and my solution (Sep. 2019) was to add a runtime confirmation of the record permission. I'm not sure if it's the same case, buuuut
Here is my code to it:
private boolean permissionToRecordAccepted = false;
private String [] permissions = {Manifest.permission.RECORD_AUDIO};
private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case REQUEST_RECORD_AUDIO_PERMISSION:
permissionToRecordAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
break;
}
if (!permissionToRecordAccepted ) finish();
}

Why Android libslide menu with actionbarsherlock open automatically?

I have a project with the sliding menu (from jeremy feinstein) and actionbarsherlock.
For some reason, when the activity shows up the slide menu open automatically too.
Quick note about my app architecture:
All of my activities have the slide menu integrated and on menu item click I start the related activity (with FLAG_ACTIVITY_SINGLE_TOP).
All my activities extends the class shown below.
This is quite annoying because every time the user click on one item, the menu get expanded as well forcing the user to close it down.
Anyone knows what it is causing this behavior?
What should I do to fix it and have the expected behavior.
I post below the concerned code:
package com.example.mypapp;
import com.example.mypapp.R;
import ocom.example.mypapp.SampleListFragment;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;
public class MyAppBaseActivity extends SlidingFragmentActivity {
protected ListFragment mFrag;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setBehindContentView(R.layout.menu_frame);
SlidingMenu sm = getSlidingMenu();
sm.setShadowWidthRes(R.dimen.shadow_width);
sm.setShadowDrawable(R.drawable.shadow);
sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
sm.setFadeDegree(0.35f);
sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
if (savedInstanceState == null) {
FragmentTransaction t = this.getSupportFragmentManager().beginTransaction();
mFrag = new SampleListFragment();
t.replace(R.id.menu_frame, mFrag);
t.commit();
} else {
mFrag = (ListFragment)this.getSupportFragmentManager().findFragmentById(R.id.menu_frame);
}
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
toggle();
}
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
toggle();
return true;
}
}
Where SlidingFragmentActivity has been modified to extend SherlockFragmentActivity as suggested on official page of Jeremy Feinstein when actionbarsherlock is also in the picture.

LWUIT assistance

import com.sun.lwuit.Button;
import com.sun.lwuit.Command;
import com.sun.lwuit.Display;
import com.sun.lwuit.Label;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.plaf.UIManager;
import com.sun.lwuit.util.Resources;
import java.io.IOException;
public class Ruwwa extends javax.microedition.midlet.MIDlet
implements ActionListener{
Form f;
Button mybutton1;
Button mybutton2;
Command exit;
Command ok;
public void startApp() {
Display.init(this);
f = new Form();
try {
Resources r = Resources.open("/mairuwa.res");
UIManager.getInstance().setThemeProps(r.getTheme("Mairuwa Theme"));
} catch (IOException ioe) {
ioe.printStackTrace();
}
mybutton1=new Button("Report A Problem");
mybutton2=new Button("Request Info");
f.setLayout(new BorderLayout());
f.addComponent(BorderLayout.CENTER, new Label("The Mairuwa Portal"));
ok = new Command("OK");
exit = new Command("Exit");
f.addCommand(ok);
f.addCommand(exit);
f.addCommandListener(this);
f.show();
}
public void pauseApp() {}
public void destroyApp(boolean unconditional) {}
public void actionPerformed(ActionEvent ae) {
notifyDestroyed();
}
}
I would like to add another label under the "The Mairuwa Portal" and also place two buttons ("Report A Problem","Request Information") beneath this as well. An illustration of what I am describing is
label: The Mairuwa Portal
then another label beneath it: I want to:
Then two buttons beneath this Button:Report Problem Button: Request Information
I have been able to add OK and EXIT button to the project,but this above buttons I talked about should as I described.
These buttons will carry functionality. I hope this can be done in LWUIT.
You need to include all JSR's when compiling a LWUIT application in the IDE. LWUIT doesn't require them all to run but requires 184, 226, MMAPI & file connector to compile. This is causing your verification error.
I would recommend developing with the Sun/Oracle simulators and using the more device like emulators for QA.
The exception you got means your application was built incorrectly, see that Ruwwa is in the jar file that was produced by your build. If not fix your build.

Resources