How can i create different pages without using activities - java

I'm trying to create an app that has different pages for topics and questions. I have created about two activites and am about to create more, like 40 activities. How can I do this without creating up to that number of activities?
Here is my MainActivity.java codes
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private ListView mListView;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Declare the text view id
mListView = (ListView) findViewById(R.id.myList);
//Adding text to the array list
String booksArray[] = new String[]{"General Questions", "Mathematics",
"Physics",
"Chemistry",
"English"};
//Initialize the array list in the adapter
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout
.simple_list_item_1, booksArray);
mListView.setAdapter(adapter);
//Set the listener for the list view item
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
//if the position of item clicked is 1, it should open
//another activity
if(position == 1 ){
conditionOfIf();
}
else{
//A short message that notify user for an error
Toast.makeText(getApplicationContext(), "Please click on the first objcet",
Toast.LENGTH_LONG)
.show();}
}
});
}
//The real code that open another activity called Topics
private void conditionOfIf(){
Intent intent = new Intent(this, Topics.class);
startActivity(intent);
}
}

Fragments is your answer. your can create 40 fragments and have only one activity for managing that fragments.
And the best thing about fragments is that you can use the same UI for multiple purpose i.e reuse-ability which might come handy as you have large number of layouts.
i think this will be a great Fragment tutorial to start with,it is easy to understand yet powerful enough to teach you the fundamentals.

use fragments.
For learning fragments go to google or youtube videos.
There are many online sources available.

Related

How to create a list view that makes a window with information pop-up?

Im just starting out with android studio and ive run into this block with an app that im trying to build.
Ive created a list view with the names of COVID vaccines, I want to code in such a way that when the user clicks on a vaccine a window/new activity pops up that shows them all the info about the vaccine in the form of a table.
How can I do that?
This is the Coding I have so far:
package com.example.covid_vaccine;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listViewVaccines = (ListView) findViewById(R.id.listView);
ArrayAdapter<CharSequence> adapterVaccines = ArrayAdapter.createFromResource(this,
R.array.vaccineArray,
android.R.layout.simple_list_item_1);
listViewVaccines.setAdapter(adapterVaccines);
}
}
You need to add OnItemClickListener in your adapter class
If you are new to Android studio see this tutorial from youtube to add OnItemClickListener it may help you
https://youtu.be/bhhs4bwYyhc
Happy coding:)

AndroidStudio, ArrayList+SearchBar, how to get correct Activity

I am a beginner and I have a project to do for school. So the problem is, that whenever I try to open a new Activity on the Emulator by clicking on the listed entries I get to the activity, so far so good but the problem is because of the search bar, the positions of the entries changes. So as far as you can see in my code, Cyberpunk will always be the first entry and Dark Souls the second. But if I specificaly look for Dark Souls in the searchBar (it will only show up Dark Souls) I am getting Cyberpunk activity as a result since it is on position 1.
(I didn't finish all activities for the other entries yet, trying to fix this issure first)
I've already tried stuff like if, switch etc. but I just get the same result. I would really appreciate any help! :)
Regards
Here is my Code:
package at.fh.joanneum.smartplay;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
public class Searchlist extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_searchlist);
final ArrayList<String> listGames = new ArrayList<>();
listGames.add("Cyberpunk");
listGames.add("Anno 1800");
listGames.add("Dark Souls 3");
listGames.add("Battlefield V");
listGames.add("Minecraft");
listGames.add("DayZ");
listGames.add("Counter Strike");
final ArrayList<Class> intents = new ArrayList<Class>();
intents.add(Cyberpunk.class);
intents.add(DarkSouls.class);
ListView myListView = (ListView) findViewById(R.id.listview_activity_Searchlist);
final ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, listGames);
myListView.setAdapter(adapter);
SearchView mySearchView = (SearchView) findViewById(R.id.searchBar);
mySearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String list) {
adapter.getFilter().filter(list);
return false;
}
});
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent listIntent = new Intent(getApplicationContext(),
intents.get(position));
startActivity(listIntent);
}
});
}
}
The top item is always the item at first index. Since you filter your adapter you change the order of items and therefore their positions, but you don't account for that when loading the Intent from your Intent List in the itemClick callback. You should either create a complex object that contains the display text and the Intent so when onClick is called, you can retrieve the clicked item and get the Intent from it. Or you can create a mapping of item-id and intent and then use the id-parameter of the click callback to retrieve the correct Intent. I would recommend the first solution.
Create a object like
class GameData{
private String text;
private Intent intent;
public GameData(String text, Intent intent){
this.text = text;
this.intent = intent;
}
public Intent getIntent(){
return intent;
}
public String toString(){
return text;
}
}
and fill your ArrayAdapter with those objects instead of Strings. Once the item is clicked, retrieve the item for the clicked position from the adapter and call its getIntent() method. This will deliver the desired Intent.

How do I launch a specific instance of a class with an intent?

I'm having trouble launching an instance of a class with an intent.
My app has an initial screen with three textviews 'Cakes, Drinks, and Biscuits'. An onClick listener is set on these textviews, such that when the user clicks on 'Cakes' it goes to a list of cakes (Chocolate, Lemon, Carrot), and the user clicks on 'Drinks' it goes to a list of drinks (Tea, Coffee, Coke), and the same for Biscuits. Currently, I have an intent that launches a Cakes class, and within that class there is an arrayList that has strings (Chocolate, Lemon, Carrot etc.), when the user clicks on Drinks it launches a separate class called Drinks and does the same, ditto with Biscuits. However, I gather it is better coding practice to have simply one class for these three, and have separate instances of that class (with different arrayLists to separately list the cake, drinks and biscuits).
I assume I should make an 'items' class (i.e. the arrayList with Chocolate, Lemon, Carrot, and all the drinks, and all the biscuits) but don't know how to launch a specific instance of the 'items' class with my intent written in the mainActivity. Any help appreciated!
The mainActivity.java where the initial three items are listed:
package com.example.android.recipe;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView history = (TextView) findViewById(R.id.cakes);
history.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cakesList = new Intent(MainActivity.this, cakeActivity.class);
startActivity(cakesList);
}
});
TextView examination = (TextView) findViewById(R.id.drinks);
examination.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent drinksIntent = new Intent(MainActivity.this, drinksActivity.class);
startActivity(drinksIntent);
}
});
TextView other = (TextView) findViewById(R.id.biscuits);
other.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent biscuitsIntent = new Intent(MainActivity.this, BiscuitsActivity.class);
startActivity(biscuitsIntent);
}
});
}
}
This is the 'CakeActivity.java' which gets launched when you click on 'Cakes', I would like to turn this into a generic class which gets launched when you click on Cakes, Coffee, or Biscuits but it comes up with the relevant ArrayList. NB I have a custom ArrayAdapter called 'Record' because, when I further develop this app, clicking on Chocolate, Lemon, etc. will have a list of separate ingredients required to make that Cake (these will also in the future not be separate classes).
package com.example.android.recipe;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
public class cakeActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.record_list);
final ArrayList<Record> records = new ArrayList<Record>();
records.add(new Record("Chocolate", ChocolateCake.class));
records.add(new Record("Lemon", LemonCake.class));
records.add(new Record("Ginger", GingerCake.class));
RecordAdapter adapter =
new RecordAdapter(this, records, R.color.colorTan);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Record record = records.get(position);
Intent intent = new Intent(getApplicationContext(), record.getListedItemId());
startActivity(intent);
}
});
}
}
NB this is exemplary code, and not my actual app - the reason I mention this is because I am going to have a really long list that, in the way in which my code is currently written, would require >100 classes if I continued in the way I am above.
Yyou can use intent extra value:
The easiest way to do this would be to pass the type to the activity in the intent.
Intent intent = new Intent(getBaseContext(), AllInOneActivity.class);
intent.putExtra("type", "cake");
startActivity(intent);
Access that intent on next activity
String type = getIntent().getStringExtra("type");
Load your data according to type:
final ArrayList<Record> records = new ArrayList<Record>();
if(type.equals("cake"))
{
records.add(new Record("Chocolate", ChocolateCake.class));
records.add(new Record("Lemon", LemonCake.class));
records.add(new Record("Ginger", GingerCake.class));
}
else if(type.equals("Drinks"))
{
records.add(new Record("fruty", whatever.class));
}
Try this and let me know. if problem persist.

Where is the id of a string array stored or where can i create one, IN ANDROID Programming?

I am learning Android programming from this tutorial about ArrayAdapters and ListViews.
The output does not show the string array values but instead shows: Item1, subitem1,, Item2,subitemm2...etc.
I want to know why did it happen? Do the values of string array need to be created separately or does Eclipse do that automatically? If so, where would I put/find the id mobile_list?
Here is the main activity class where string array declared:
package com.example.ListDisplay;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class ListDisplay extends Activity {
// Array of strings...
String[] mobileArray = {"Android","IPhone","WindowsMobile","Blackberry","WebOS","Ubuntu","Windows7","Max OS X"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.activity_listview, mobileArray);
ListView listView = (ListView) findViewById(R.id.mobile_list);
listView.setAdapter(adapter);
}
}
Please refer to this question. You need to create your own class that extends from ArrayAdapter and override getView() so you can inflate your views accordingly and getCount() so the list view knows how many items are drawn. You are not supposed to use the default implementation of the ArrayAdapter. The default implementation and the way you are using it is taking as second parameter a TextView reference and you appear to be passing a layout. Refer to the official docs for this. That's why you need to create your own class
Change
ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.activity_listview, mobileArray);
To
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.activity_listview, mobileArray);

Unable to get list items correct code using Java

I am trying to create a list view in Java that allows each list item to open a web url address but I can not seem to get the code right. Please can some one show me where IO going wrong.
package com.sasquatchapps.hydraquip10.bestofmonsterquest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class Season1Activity extends Activity{
private String episodes[] = {"America's Loch Ness Monster","Sasquatch Attack",
"Giant Squid Found","Birdzilla","Bigfoot","“Mutant K9","Lions in the Backyard","Gigantic Killer Fish","Swamp Beast","Russia's Killer Apemen","Unidentified Flying Creatures","The Real Hobbit",
"Giganto: The Real King Kong","American Werewolf"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayAdapter<String> adapter = new
ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, episodes);
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(this, "Item clicked;" + episodes[position], Toast.LENGTH_SHORT).show();
if (position == 0) {
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("https://www.youtube.com/watch?v=o7-RdxrCFAg"));
startActivity(intent);
}
}
}
You have some errors - Where is your listview? Modify your code
1) create listview -
ListView myList;
2) In your onCreate assign this list:
myList = (ListView) findViewById(R.id.my_list);
3) Set adapter to your list:
myList.setAdapter(adapter);

Categories