How do I resolve a Redeclaration Error in Android Studio - java

This code is for a button that would be on the android emulator. However, when I place this code in the main activity.kt it gives me multiple errors. The first error I experience is a redeclaration error on line 9 on the main activity
package com.example.android.justjava
import android.R
import android.os.Bundle
import android.support.v7.app.ActionBarActivity
import android.view.View
import android.widget.TextView
// This activity displays an order form to order coffee.
class MainActivity : ActionBarActivity() {
protected fun onCreate(savedInstanceState: Bundle) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
// this method is called when the order button is clicked.
fun submitOrder(view: View) {
display(1)
}
// This method displays the given quantity value on the screen.
private fun display(number: Int) {
val quantityTextView = findViewById(R.id.quantity_text_view as TextView
quantityTextView.text = "" + number
}
}
This activity displays an order form to order coffee.
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
// This method is called when the order button is clicked.
public void submitOrder(View view) {
display(1);
}
// This method displays the given quantity value on the screen.
private void display(int number) {
TextView quantityTextView =(TextView) findViewById (R.id.quantity_text_view);
quantityTextView.setText("" + number);
}
}

File tab -> Invalidate Caches/Restart (then choose invalidate and restart from the dialog that will appear)
Build tab -> Clean Project
Build tab -> Rebuild Project
This solution is just the same as #Ehsan_Haghdoust solution but letting Android Studio do that for me instead of doing that my self.

The question is for 6 months ago, but I write my answer for others face this problem in the future. I have had challenge with this error, I checked every possible way suggested by others and I FINALLY had to delete build folders in
projectFolder/
and
projectFolder/app/
manually and rebuild the project again.

The problem you face is that you have 2 activities with the same name MainActivity - one in Java, and second in Koltin. Both classes (activities in this case) are compiled into the same application - you have 2 symbols with the same name.
yes, Koltin and Java look the same after the compiler finish with them :)

In my case, I was running the app in debug mode and a direction class was generated for debug. Then I tried generating a signed APK in release mode. Then a similar class was generated in same package for release mode which caused the issue. I manually deleted just the debug folder in the Java folder(root) and the build was successful.

Build -> Select Build Variant. It was in debug, I just changed it to release mode and done.

Related

How to get the context inside a mouse click listener

In Android Studio, developing in Java, I have the following (a somewhat minimized version of what I'm trying to do).
package com.example.japanesequiz;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
String[] hiragana = {"あ", "か"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button generate = findViewById(R.id.generate);
TextView questionText = findViewById(R.id.question_text);
RadioGroup radioGroup = new RadioGroup(this);
MainActivity ma_inst = this;
generate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Random rand = new Random();
int hir_index = rand.nextInt(2);
questionText.setText(hiragana[hir_index]);
RadioButton rb1 = new RadioButton(ma_inst);
rb1.setId(View.generateViewId());
rb1.setText("Ah");
radioGroup.addView(rb1);
RadioButton rb2 = new RadioButton(ma_inst);
rb2.setId(View.generateViewId());
rb2.setText("Ka");
radioGroup.addView(rb2);
}
});
}
}
The basic idea is that I want to have the main screen initially mostly blank, but with a button at the bottom. When tapped, it eventually show some text and a radio button group. (I haven't yet fully built out the rest, of course.)
But at this stage what I expect when I launch the app is to see the mostly blank screen, and maybe if I tap the button it will generate some text and options (that then do nothing, further implementation to come).
But the app never launches. Instead, Graddle finishes building, I get a terminal saying that it's launching the app, but it hangs and times out.
If I had to guess -- and this is a guess because I'm very new to Android development -- there is some issue with grabbing the this instance and then using it in the OnClickListener. I'm not certain what the issue is, but it's the only thing I see here that looks fishy. Also, I'm not sure how else one is supposed to add objects to the current activity from inside of the anonymous class passed into the OnClickListener since, there, a reference to this then refers to the anonymous inner class.
I know that it is possible to use a lambda instead, and that probably resolves the issue, but I want to really understand what's going on here, since it seems like it might be conceptually important for later development.
My question: If I have correctly understood this much, then how does a lambda get around this issue? If I've not correctly understood then I'd appreciate any insight, thanks!
There are many questions in one question. First, let me try to answer your title question: "How to get context inside a mouse click listener":
There are many ways, but you can consider this one (your click lisener's onClick has the signature void onClick(View view), hence you have access to view.
view.getContext()
Next, nothing wrong with these though you better migrate to view binding https://developer.android.com/topic/libraries/view-binding as butterknife is deprecated officially
Button generate = findViewById(R.id.generate);
TextView questionText = findViewById(R.id.question_text);
Next, you don't really need this trick in order to get activity in your lambda:
MainActivity ma_inst = this;
Instead and if really needed, you can always do Context context = MainActivity.this;
Lastly, I think the issue the app never launches roots into something else not related with title question you posted, unfortunately.

How do I change the main xml file from another activity?

I am very new to Java. I am doing a school project at the moment and I have my main activity, then I have a settings activity. I am trying to modify the xml from the main activity with the settings activity. I am able to modify the settings xml file with the settings.java, but I would like to modify the main activity xml with settings.java
public class Settings extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
// Get the Intent that started this activity and extract the string
Switch switchButton;
final RelativeLayout mRelativeLayout = (RelativeLayout) findViewById(R.id.activity_settings);
final RelativeLayout mRelativeLayoutMain = (RelativeLayout) findViewById(R.id.activity_main);
switchButton = (Switch) findViewById(R.id.switch1);
switchButton.setChecked(true);
switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean bChecked) {
if (bChecked) {
mRelativeLayoutMain.setBackgroundColor(Color.GRAY);
mRelativeLayout.setBackgroundColor(Color.GRAY);
} else {
mRelativeLayoutMain.setBackgroundColor(Color.WHITE);
mRelativeLayout.setBackgroundColor(Color.WHITE);
}
}
});
if (switchButton.isChecked()) {
mRelativeLayoutMain.setBackgroundColor(Color.GRAY);
mRelativeLayout.setBackgroundColor(Color.GRAY);
} else {
mRelativeLayoutMain.setBackgroundColor(Color.WHITE);
mRelativeLayout.setBackgroundColor(Color.WHITE);
}}
public void toast1(View view) {
android.widget.Toast.makeText(this, "Created by Cody Walls and Tommy Serfas", android.widget.Toast.LENGTH_LONG).show();
}
/*public void switch1(View view) {
ScrollView mScrollView = (ScrollView) findViewById(R.id.scrollView);
mScrollView.setBackgroundColor(Color.GRAY);
}*/
}
In the Code I am trying to change the background of the main activity xml with :
mRelativeLayoutMain.setBackgroundColor(Color.GRAY);
and when I run the app and click the intent it will crash with the error:
"java.lang.NullPointerException: Attempt to invoke virtual method
'void android.widget.RelativeLayout.setBackgroundColor(int)' on a null
object reference"
I think the easiest way is to create an PreferenceManager.SharedPreferences, in which I recommend you to store current app data. This will help you not to loose any changes in app after you exit the it. Here is short instructions:
Create button in settings activity which will change something in main activity.
Create onClickListener for your button.
Use .SharedPreferences to store was you button clicked or not. (I recommend storing boolean variables, this way you can store was button clicked or not.)
I both of your activities in onCreate method call .getSharedPreferences to read saved app values. (I mean to read was the button clicked or not.)
Use app values you got from 4. to change any element in activity. (For example if you stored that button was clicked, then change some TextView text or etc.)
I hope you understood the idea.
Link to the Android developer tutorial about App key values storing & saving
Link to the StackOverflow much easier explanation & examples
There are a couple of ways of doing this (Some of which depends on how you are switching back and forth from each activity). It also depends on what things you are changing.
From your settings page, as you are changing different settings, you'll save this content within Preferences. (You can see more how to use Preferences here: https://examples.javacodegeeks.com/android/core/ui/settings/android-settings-example/ or by just Googling it).
On you main activity, depending on how you come back to it (onStart most likely), you can setup the things you need to programmatically.
So, you may need to do a little research on the Android lifecycle and how each cycle works (https://developer.android.com/guide/components/activities/activity-lifecycle.html), how to program the UI programmatically through Java (http://startandroid.ru/en/lessons/220-lesson-16-creating-layout-programmatically-layoutparams.html), and the Preferences Android library to save certain settings.
The xml isn't meant to be "altered". You can change the UI programmatically. It's possible to build an Android app without any xml. When Android was first built, it didn't use the xml to create the UI. It was all done through Java. It was then added to use xml to create your activities or fragments or any UI component. This made things easier for more static activities or activities with very little dynamic content.

Call requires API level 11(current min is 8) android.app.Activity#onCreateView

I am a newbie to android, and I am developing an android application. But my package line gives this error in MainActivity.java class.
Could anyone please tell me the reason of this?.
This is my class and the package line gives this error.
package com.example.eventgyaam;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int counter;
Button add,sub;
TextView display;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter = 0;
add = (Button) findViewById(R.id.bAdd);
sub = (Button) findViewById(R.id.bSub);
display = (Button) findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter++;
display.setText("Your total is "+counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter--;
display.setText("Your total is "+counter);
}
});
}
}
For each Android API, there might be new features added, which can't work on lower API versions. Thus, to fix this, you can just increase the minimum required API in your project.
In your build.gradle (app-module), you will find this line:
minSdkVersion 8
Change it to:
minSdkVersion 11
If you didn't find this line in build.gradle, check your AndroidManifest.xml and change the minSdkVersion from 8 to 11 or whatever you want:
<uses-sdk
android:minSdkVersion="11" />
But now your app will only work on API 11+, which is fine. Nobody uses below API 11 these days, so it shouldn't be a problem for you.
First, some introductory details. There are levels of Android API and, at each level, they may introduce new functionality , as per here.
When you create an Android application, you specify the minimum level that your application will run on. This is done in the manifest with the uses-sdk stanza: see here for details.
So, if you use functionality that's only available at level 11, your code won't run on a level 8 API like you've specified.
You either have to use only what's available at your current minimum, or up the minimum.
As to why you appear to be getting the error on the package line, and for a call that doesn't seem to be in the source code you've shown us, I couldn't say. Since it's complaining about android.app.Activity#onCreateView as per your title, there may be an issue with the view R.layout.activity_main that's being inflated by setContentView. Or it may be an issue with the compatibility library itself, something that's not unheard of.
However, rather than struggling too hard with this, you may want to consider simply upping the minimum to API-11 and dropping the appcompat stuff altogether. As per here, only about 2% of Android users are still back on releases earlier than Android-3.0/API-11 (as of June 2016). That's only likely to get smaller as time goes by.
Error:
Call requires API level 11(current min is 8)
android.app.Activity#onCreateView
If you take a look at the javadoc for the Activity class you'll see that the method public View onCreateView (View parent, String name, Context context, AttributeSet attrs) was added in API 11 that is why you are getting this error.
Either You have to Change your minSdkVersion from 8 to 11
Or you Use #SuppressLint("NewApi") at the class declaration level as workaround for Activity like this:
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
For Fragment:
#SuppressLint("NewApi")
#Override
public void View onCreateView(String name, Context context, AttributeSet attrs) {
#SuppressLint("NewApi") is an annotation used by the Android Lint tool.
Lint will tell you whenever something in your code isn't optimal or may crash. By passing NewApi there, you're suppressing all warnings that would tell you if you're using any API introduced after your minSdkVersion
EDIT:
You can also use #TargetApi(11) instead of #SuppressLint("NewApi"). More difference between these can be found here.
Hope it helps!
Because fragments added in API 11 and your current minSDK = 8, you can see that here
Your are using AppCompatActivity which calls Fragment class in onCreateView() method, Although your code doesn't implement onCreateView() but AppCompatActivity does. you can read the source code here
Solution there are two possible solution
1- change sdk version in manifest to >= 11
2- (if you use API below 11) use SuppressLint annotation to suppress any error related to sdkVersion and implement onCreateView as follows
#SuppressLint("NewApi")
public View onCreateView(View parent, String name, Context context, AttributeSet attrs)
{
if (Build.VERSION.SDK_INT >= 11)
return super.onCreateView(parent, name, context, attrs);
return null;
}
change your minsdkversion from manifest.xml
<uses-sdk
android:minSdkVersion="11"/>
I faced the same issue and I resolved it by changing the superclass of my activity.
Insted of "public class MainActivity extends AppCompatActivity",
I typed "public class MainActivity extends Activity".
After the change the issue got resolved.
If you are using Eclipse, right click on one of your projects and click properties, select Java Compiler from left list, uncheck "Enable project specific settings", click on Configure Workspace Settings link, change Compiler compliance level to the highest version (for now it's 1.8).
then click OK and accept everything it asked.
Also to make sure, change Project Build Target api of all of your projects to the latest api.
EDIT:
I personally had to uncheck "Enable project specific settings" for all of library projects one by one. changed Compiler compliance level of workspace to 1.8 then checked "Enable project specific settings" only for my own main project and changed its Compiler compliance level to 1.6.

Just update ADT and Unable to resolve superclass errer appear

The error show after I update my ADT, the project is created before the update.
In Login Activity,
public class LoginActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Do something here... if login success, Start another activity
Intent i = new Intent(LoginActivity.this, MainActivity.class);
LoginActivity.this.startActivity(i);
}
.......
}
In MainActivity,
public class MainActivity extends FragmentActivity {
protected void onCreate(Bundle savedInstanceState) {
//......
}
}
I try to remove all the code inside and back to a blank activity. The error is not happen because of the code inside the activity. I think is abut the extend FragmentActivity
Here is the error trace:
Unable to resolve superclass of Lhk/iactive/imoodle/activity/MainActivity; (15)
Link of class 'Lhk/iactive/imoodle/activity/MainActivity;' failed
I get this error after I update my ADT.
I do some research on this topic. I try to import the android-support-v4.jar again and this do not fix the problem.
I also read some blog like THIS ONE can not help me too :(
I have solve the problem by myself. I am going to share the solution hope there is other people who suffer from the same error can save some time :D
I try many method for example go to build Path Config -> Order and Exprot, All the library is already checked. And the NoClassPathFound error is still showing.
I have no external Jar for the project and The error is from FragmentActivity from Android Support Library.
Then I delete the android-support-v4.jar complete and add it again by right clicked the project -> Android Tools -> Add support library...
After the new support library added. All the error fix. :D
This worked for me:
For all projects (app and library):
Right click the project, and choose Properties
Go to Java Build Path-Order and Export.
Tick 'Android Private Libraries'

Main layout not recognized, immediately after starting new Android project

The below code was automatically generated when I started a new android project.
I'm getting an error on the "R.layout.main" saying it does not exist.
I do in fact have a main.xml and I can see the layout change as I edit it in the Graphical Layout tab.
How can I fix this so I can run my application?
public class ComplimentGeneratorActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
The package name of the R file and the package name of your source code may not match. Make sure the package your code is in is the same as the package defined in the manifest file. Otherwise you will need to import the R file with the full package name (ex: com.example.R.layout.main).
If they match, for some reason your R file was not generated properly. Try cleaning your project.
Also, start accepting some answers. I almost didn't answer this because of your horrible acceptance rate.
This may be a very simple answer, but it has happened to me before. Try to restart eclipse. File -> Restart
Try to import the R.java file with the full path inside the main activity class file...
import com.example.packagename.R;
Hope, this will solve your query.

Categories