Android Studio - How to open specific activities from a ListView? - java

I´ve got problems to finish my code to open activities from a list that I made. I´m making an app of equations and I want to have a list of the subjects and when you click on one, it starts the .xml file that have the equations that I already have. I got already the activities stringed to java classes.
Here is my code:
MainActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_principal);
//get list view from xml
temasListView = (ListView) findViewById(R.id.temasListView);
String[] Temas = {
"Conversion",
"Suma",
"Trigonometria",
"Primera",
"Momento",
"Centro",
"Segunda1",
"MRU",
"MRUA",
"Tiro",
"Segunda2"};
ListAdapter temasAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, Temas);
ListView temasListView = (ListView) findViewById(R.id.temasListView);
temasListView.setAdapter(temasAdapter);
temasListView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String temas = String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(Temas.this, temas, Toast.LENGTH_LONG).show();
if (position == 0) {
Intent intent = new Intent(this, Conversion.class);
startActivity(intent);
}
else if (position == 1) {
Intent intent = new Intent(this, Suma.class);
startActivity(intent);
}
else if (position == 2) {
Intent intent = new Intent(this, Trigonometria.class);
startActivity(intent);
}
else if (position == 3) {
Intent intent = new Intent(this, Primera.class);
startActivity(intent);}
else if (position == 4) {
Intent intent = new Intent(this, Momento.class);
startActivity(intent);
}
else if (position == 5) {
Intent intent = new Intent(this, Centro.class);
startActivity(intent);
}
else if (position == 6) {
Intent intent = new Intent(this, Segunda1.class);
startActivity(intent);
}
else if (position == 7) {
Intent intent = new Intent(this, MRU.class);
startActivity(intent);
}
else if (position == 8) {
Intent intent = new Intent(this, MRUA.class);
startActivity(intent);
}
else if (position == 9) {
Intent intent = new Intent(this, Tiro.class);
startActivity(intent);
}
else if (position == 10) {
Intent intent = new Intent(this, Segunda2.class);
startActivity(intent);
}
});
}
strings.xml:
<resources>
<string name="app_name"></string>
<string-array name="temas">
<item>Conversión de Unidades</item>
<item>Suma de Vectores</item>
<item>Trigonometría</item>
<item>Primera Ley de Newton</item>
<item>Momento de Fuerzas</item>
<item>Centro de Gravedad</item>
<item>Componente de Velocidad</item>
<item>Segunda Ley de Newton</item>
<item>Movimiento Rectilíneo Uniforme</item>
<item>MRUA</item>
<item>Tiro Vertical</item>
<item>Segunda Ley de Newton (DCL)</item>
</string-array>
And my principal activity:
<LinearLayout
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:entries="#array/temas"
android:id="#+id/temasListView"
android:layout_weight="1.05"
android:background="#dadada" />
</LinearLayout>
I need help to finish this please!

When you are inside anonymous inner class this will not refer to your current activity class.
You should use MainActivity.this instead of this
i.e
Intent intent = new Intent(MainActivity.this, Conversion.class);
startActivity(intent);
You can refactor your code like this, to get rid of switch case.
String className= parent.getItemAtPosition(position).toString();
Class myClass=Class.forName("yourpackagename"+className);
Intent intent = new Intent(MainActivity.this, myClass);
startActivity(intent);
No need to use many switch conditions.
Also as pointed in above answer use MainActivity.this instad of Temas.this in your toast message

Change this line from
Toast.makeText(Temas.this, temas, Toast.LENGTH_LONG).show();
to
Toast.makeText(MainActivity.this, temas, Toast.LENGTH_LONG).show();

Related

Resource IDs will be non-final by default in Android Gradle Plugin version 8.0, avoid using them in switch case statements

I have an warning in Android Studio about my navigation drawer resources. Warning is Resource IDs will be non-final by default in Android Gradle Plugin version 8.0, avoid using them in switch case statements. I tried to use the method if to update my code but I won't 'converted right'. I found on the internet this article to help me to convert my code but it seem not work for me. I want to know if I miss something.
Down below is before and after to make an idea and here is my full activity because I saw lot of people have this after used public void onClick... and I don't use it. I have navigationView.setNavigationItemSelectedListener(menuItem -> {.
Before:
navigationView.setNavigationItemSelectedListener(menuItem -> {
switch (menuItem.getItemId())
{
case R.id.nav_drawer_settings:
Intent intent = new Intent (MainActivity.this, SettingsActivity.class);
startActivity(intent);
break;
case R.id.nav_drawer_whitelist:
intent = new Intent (MainActivity.this, WhitelistActivity.class);
startActivity(intent);
break;
case R.id.nav_drawer_clipboard_cleaner:
intent = new Intent (MainActivity.this, ClipboardActivity.class);
startActivity(intent);
break;
case R.id.nav_drawer_invalid_media_cleaner:
intent = new Intent (MainActivity.this, InvalidActivity.class);
startActivity(intent);
break;
case R.id.nav_drawer_about:
intent = new Intent (MainActivity.this, AboutActivity.class);
startActivity(intent);
break;
case R.id.nav_drawer_support:
Intent newIntent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("https://www.paypal.me/d4rkmichaeltutorials"));
startActivity(newIntent);
break;
case R.id.nav_drawer_share:{
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "https://play.google.com/store/apps/details?id=com.d4rk.cleaner";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"Try right now!");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share using..."));
}
break;
}
return false;
});
}
After:
navigationView.setNavigationItemSelectedListener(menuItem -> {
switch (view.getId()) {
if (item.getItemId() == R.id.nav_drawer_settings) {
Intent intent = new Intent (MainActivity.this, SettingsActivity.class);
startActivity(intent);
}
if (item.getItemId() == R.id.nav_drawer_whitelist) {
Intent intent = new Intent (MainActivity.this, WhitelistActivity.class);
startActivity(intent);
}
if (item.getItemId() == R.id.nav_drawer_clipboard_cleaner) {
Intent intent = new Intent (MainActivity.this, ClipboardActivity.class);
startActivity(intent);
}
if (item.getItemId() == R.id.nav_drawer_invalid_media_cleaner) {
Intent intent = new Intent (MainActivity.this, InvalidActivity.class);
startActivity(intent);
}
if (item.getItemId() == R.id.nav_drawer_about) {
Intent intent = new Intent (MainActivity.this, AboutActivity.class);
startActivity(intent);
}
if (item.getItemId() == R.id.nav_drawer_support) {
Intent openURL = new Intent(Intent.ACTION_VIEW);
openURL.setData(Uri.parse("https://www.paypal.me/d4rkmichaeltutorials"));
startActivity(openURL);
}
if (item.getItemId() == R.id.nav_drawer_share) {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "https://play.google.com/store/apps/details?id=com.d4rk.cleaner";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"Try right now!");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share using..."));
}
}
return false;
});
}
Thanks in advance! :D
On the after code that you posted, there is no need anymore for the switch.
It should work only by writing the following:
if (item.getItemId() == R.id.nav_drawer_settings) {
Intent intent = new Intent (MainActivity.this, SettingsActivity.class);
startActivity(intent);
}
if (item.getItemId() == R.id.nav_drawer_whitelist) {
Intent intent = new Intent (MainActivity.this, WhitelistActivity.class);
startActivity(intent);
}
if (item.getItemId() == R.id.nav_drawer_clipboard_cleaner) {
Intent intent = new Intent (MainActivity.this, ClipboardActivity.class);
startActivity(intent);
}
if (item.getItemId() == R.id.nav_drawer_invalid_media_cleaner) {
Intent intent = new Intent (MainActivity.this, InvalidActivity.class);
startActivity(intent);
}
if (item.getItemId() == R.id.nav_drawer_about) {
Intent intent = new Intent (MainActivity.this, AboutActivity.class);
startActivity(intent);
}
if (item.getItemId() == R.id.nav_drawer_support) {
Intent openURL = new Intent(Intent.ACTION_VIEW);
openURL.setData(Uri.parse("https://www.paypal.me/d4rkmichaeltutorials"));
startActivity(openURL);
}
if (item.getItemId() == R.id.nav_drawer_share) {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "https://play.google.com/store/apps/details?id=com.d4rk.cleaner";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"Try right now!");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share using..."));
}
even if you put case R.id.nav_drawer_settings: AS case (R.id.nav_drawer_settings): in bracket it will work
If one just wants to suppress this warning for the whole application, add this to ones build.gradle file:
android {
lintOptions {
disable 'NonConstantResourceId'
}
}

Android Studio Beginner;

So here's my code:
public class MainActivity extends AppCompatActivity {
/* access modifiers changed from: protected */
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_main);
}
public void onClick(View view) {
Intent intent;
switch (view.getId()) {
case R.id.button: // Text
intent = new Intent(this,"Faiz Ahmed \nLove music forever\nTCSS 450");
break;
case R.id.button2: // Image
intent = new Intent(this, ImageActivity.class);
break;
case R.id.button3: // Web
intent = new Intent("android.intent.action.VIEW");
intent.setData(Uri.parse("http://developer.android.com"));
break;
case R.id.button4: // Toast
Toast.makeText(this, "Here's to a new quarter!", Toast.LENGTH_SHORT)
.show();
break;
case R.id.button5: // Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("I am a dialog").setTitle("Some Title").create().show();
}
intent = null;
if (intent != null) {
startActivity(intent);
}
}
}
All the import's are there I just for some reason none of the buttons are working. The first 2 (Text & Image) I know I need a lot more code, but the last 3 should work & they're not for some reason. Any know what I'm doing wrong & how to fix it?
Nothing of the buttons will work because in the switch-case statement you initialize the intent according to which button was pressed.
After that you set intent to null and lastly you start the activity if the intent is not null, but it always is (since you set it before to null).
Short story delete intent = null; statement.
// intent = null; delete this line
if (intent != null) {
startActivity(intent);
}

Java Android simple refactoring

How to improve the code below? I'm new to Java, coming from iOS background. I think intent needs to go to a separate variable.
public void activityOpener(int a) {
if (a == 1) {
Intent intent = new Intent (this, proj1new.class);
startActivity(intent);
}else {
Intent intent = new Intent (this, BasicNumbers.class);
startActivity(intent);
}
}
public void activityOpener(int a) {
Intent intent;
if (a == 1) {
intent = new Intent (this, proj1new.class);
}else {
intent = new Intent (this, BasicNumbers.class);
}
startActivity(intent);
Is that what you mean? Code is now a bit cleaner
I'd refactor it like this:
public void activityOpener(int a) {
Class<?> cls = a == 1
? proj1new.class
: BasicNumbers.class;
Intent intent = new Intent(this, cls);
startActivity(intent);
}
Not much of a change, but it makes clear that only the new activity class depends on a.
If your style is to go for brevity, the whole thing can be reduced to a one-liner (at the expense of flexibility if you want to expand the logic in the future):
public void activityOpener(int a) {
startActivity(new Intent(this, a == 1 ? proj1new.class : BasicNumbers.class));
}

New Activity from ListView

I'm working on a music sheet app, and have a bunch of songs in a ListView.
I'm using an onItemClick method, but the problem is, I don't know how to open an activity depending on what subitem is selected.
The array of songs is uta[], so I can find the specific String with uta[position], but how can I open a specific activity based off of the position that is picked by the user in the ListView?
You can make a switch/case statement on the String that you fetch with uta[position]
public void onItemClick(AdapterView parent, View v, int position, long id) {
String value = uta[position].getValue();
switch(value){
case "value1":
Intent intent = new Intent(this, activity1.class); startActivity(intent);
break;
case "value2":
Intent intent = new Intent(this, activity2.class); startActivity(intent);
break;
case "value3":
Intent intent = new Intent(this, activity3.class); startActivity(intent);
break;
}
}
Note: switch/case statement on Strings requires JDK 7, see the Oracle documentation.
Try in this manner in your onitemclick method
if (position == 0) {
Intent intent = new Intent(this, activity1.class);
startActivity(intent);
} else if (position == 1) {
Intent intent = new Intent(this, activity2.class);
startActivity(intent);
} else if (position == 2){
Intent intent = new Intent(this, activity3.class);
startActivity(intent);
}
Your ListView item-click listener provides the view that has been clicked:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Song song = (Song) getItemAtPosition(position);
if (song.getId() == SOME_ID)
startActivity(new Intent(this, SomeActivity.class));
// you can then create the logic for all your activities
}
});
Also, you may pass the song to one activity that would load itself based on the song data. For that, I recommend you read about the Parcelable interface and how to put Extras in an Intent.
Can you use:
listView1.setOnItemClickListener(new AdapterView.onItemClickListener() {
#Override
public void onItemClick(AdapterView adapter, View view, int position, long arg) {
switch (position) {
case 0:
startActivity(new Intent(this, first_activity.class));
break;
case 1:
startActivity(new Intent(this, second_activity.class));
break;
// and more...
}
});
Cheers!

How to assign value in button and display the value at other activity?

I want to make the ImageView work as button, because I want it be able to click and go to another activity. Each imageView(button) should contain its own value. The problem is, I don't know how to pass the value in the imageView(button) to another activity. This is what I have tried so far:
public class ButtonClickHandler implements View.OnClickListener {
public void onClick(View view) {
String value = " ";
switch(view.getId())
{
case R.id.imageView2:
value = "5";
break;
case R.id.imageView6:
value = "10";
break;
case R.id.imageView3:
value = "30";
break;
case R.id.imageView02:
value = "50";
break;
case R.id.imageView06:
value = "100";
break;
default:
break;
}
if(view.getId()==R.id.imageView2){
//get the value from switch case and send to other activity
}
Try this way,hope this will help you to solve your problem.
public class ButtonClickHandler implements View.OnClickListener {
public void onClick(View view) {
switch (view.getId()) {
case R.id.imageView2:
Intent intent = new Intent(YourCurrentActivity.this, YourOtherActivity.class);
intent.putExtra("YourKeyName", "5");
startActivity(intent);
break;
case R.id.imageView6:
Intent intent = new Intent(YourCurrentActivity.this, YourOtherActivity.class);
intent.putExtra("YourKeyName", "10");
startActivity(intent);
break;
case R.id.imageView3:
Intent intent = new Intent(YourCurrentActivity.this, YourOtherActivity.class);
intent.putExtra("YourKeyName", "30");
startActivity(intent);
break;
case R.id.imageView02:
Intent intent = new Intent(YourCurrentActivity.this, YourOtherActivity.class);
intent.putExtra("YourKeyName", "50");
startActivity(intent);
break;
case R.id.imageView06:
Intent intent = new Intent(YourCurrentActivity.this, YourOtherActivity.class);
intent.putExtra("YourKeyName", "100");
startActivity(intent);
break;
default:
break;
}
}
};
String valueFromIntent = getIntent().getStringExtra("YourKeyName");
Intent intent = new Intent(YourSecondActivity.this, YourThirdActivity.class);
intent.putExtra("YourKeyName", valueFromIntent);
startActivity(intent);
You can use :
Intent i = new Intent(MainActivity.this,SecondActivity.class);
i.putExtra("YourValueKey", value);
startActivity(i);
here
if(view.getId()==R.id.imageView2){
//here
}
then you can get it from your second activity by :
Intent intent = getIntent();
String YourtransferredData = intent.getExtras().getString("YourValueKey");
You can use Bundle to do the same in Android
//Create the intent
Intent i = new Intent(this, ActivityTwo.class);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
String getrec=textView.getText().toString();
//Create the bundle
Bundle bundle = new Bundle();
//Add your data to bundle
bundle.putString(“imagebuttonValue”, getrec);
//Add the bundle to the intent
i.putExtras(bundle);
//Fire that second activity
startActivity(i);
Now in your second activity retrieve your data from the bundle:
//Get the bundle
Bundle bundle = getIntent().getExtras();
//Extract the data…
String imagebuttonValue = bundle.getString(“imagebuttonValue”);
Using Intent you can call another activity and even send data with the help of putExtra from one activity to another activity, simply check below piece of code for understanding:
Intent intent= new Intent(currentActivity.this,nextActivity.class);
intent.putExtra("Key",yourvalue);
startActivity(intent);
On next acitivty to retrieve data:
Intent intent = getIntent();
String yourvalue= intent.getExtras().getString("Key");
Pass data trough Intent to your next activity and get your data in that activity like this
Intent intent = new Intent(Activity.this,SecondActity.class);
intent.putExtra("key",value);
startActivity(intent);
Get like this :
Intent intent = getIntent();
String value = intent.getStringExtra("key");
u want to launch a new activity and pass the label value to that ?
if yes then just create an Intent and add the value to it , and use this intent to launch other acitivty.
for example if your value is "5" then :-
Intent intent = new Intent(context) ;
intent.putExtra("key","5");
(refer here)
startActivity(intent);
and at onCreate() method of newly launched activity :-
String value= getIntent.getStringExtra("key"); (Refer here )
Get the values from the Image view. Use Extras and send it to the other Activity.
Lets Say first Activity is X and Next Activity is Y :-
//Include this in your code in the first activity inside your if condition
if(view.getId()==R.id.imageView2){
Intent main= new Intent(X.this, Y.class);
main.putExtra("key", value);
X.this.startActivity(main);
}
At Y Activity onCreate
Intent intent = getIntent();
String value= intent.getStringExtra("key");
Hope it helps.
Thanks!

Categories

Resources