What I am trying to do here is to display a list of strings using ArrayList<String> and ArrayAdapter<String> when a user clicks a button. I want to declare all the members i.e. adapter, ArrayList and the list layout as global because I want to add more buttons later with the same feature of displaying a list of strings.
This code has no error but it's not working. I put the Toast in the onClick to make sure the onClick is working. I can see the toast but not the listView I want to see.
class file
R.id.button_news is the button id. R.layout.activity_primary_content is the layout that I'm using in this class PrimaryContent
R.layout.list_view_secondary is the layout where the listView R.id.list_view is located.
R.layout.list_view_secondary layout and the PrimaryContent class are not related but I want to use the listView which is in the list_view_secondary layout to display from the PrimaryContent.
In this line of code
arrayAdapter = new ArrayAdapter<>(view.getContext(),android.R.layout.simple_list_item_1,list); I tried by put the context view.getContext() and getBaseContext() both of them are not working.
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class PrimaryContent extends AppCompatActivity {
private final String LOG_TAG = PrimaryContent.class.getSimpleName();
public ListView listView;
public ArrayList<String> arrayList;
public ArrayAdapter<String> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_primary_content);
final LayoutInflater factory = getLayoutInflater();
final View rootView = factory.inflate(R.layout.list_view_secondary, null);
listView = rootView.findViewById(R.id.list_view);
arrayList = new ArrayList<>();
for (int i=0; i<20; i++) {
arrayList.add("World News");
}
Button news = findViewById(R.id.button_news);
news.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getBaseContext(),"Damn",Toast.LENGTH_SHORT).show();
for (String x: arrayList) {
Log.v(LOG_TAG,x);
System.out.println();
}
arrayAdapter = new ArrayAdapter<>(view.getContext(),android.R.layout.simple_list_item_1,arrayList);
listView.setAdapter(arrayAdapter);
}
});
}
}
R.layout.list_view_secondary
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="true"
android:orientation="vertical" />
You forgot to add the inflated layout to your parent layout, for example:
LinearLayout parentLayout = (LinearLayout) findViewById(R.id.parent_layout);
parentLayout.addView(rootView);
Related
I'm beginner in Android development &
I am making a calculator app and want to update history in second fragment but not able to find a perfect solution for updating ListView in second fragment.
I tried many solutions but none of them worked properly.
I'm using ViewPager to swipe between calculator and history fragments.
I tired bundle class but if I use bundle in OnCreat method of first Fragment(CalculatorFragment) with ViewPager it shows me blank screen after starting an App & if I use Bundle class in Equal Button it crashes app.
here I am passing id of viewPager as Container of fragments.
what I want to achive.
I want to update history in second fragment(HistoryFragment) when ever "=" button is clicked.
here's a sample code of what I have done in my code so far.
MainActivity.java
package com.example.calculatorslide;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
ViewPager viewPager;
pageAdapter pageAdapter;
#RequiresApi(api = Build.VERSION_CODES.M)
#SuppressLint({"SetTextI18n", "UseCompatLoadingForDrawables"})
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = findViewById(R.id.viewPager);
//Get rid of ActionBar
ActionBar actionBar = getSupportActionBar();
assert actionBar != null;
actionBar.hide();
pageAdapter = new pageAdapter(getSupportFragmentManager(), 2);
viewPager.setAdapter(pageAdapter);
getSupportFragmentManager().beginTransaction().add(R.id.ViewPager,
new Calculatorfragment()).commit;
}
}
Example of what I am doing in when Equal button is clicked in CalculatorFragment
public void Equals() {
String calc = etCalc.getText().toString();
if (calc.split("\\+").length == 2) {
String[] calculation = calc.split("\\+");
String Ans = String.valueOf(Double.parseDouble(calculation[0]) + Double.parseDouble(calculation[1]));
etCalc.setText(Ans);
tvCalc.setText(calc);
HistoryFragment fragment = new HistoryFragment();
Bundle bundle = new Bundle();
bundle.putString("key", calc+"="+Ans);
fragment.setArguments(bundle);
getFragmentManager().beginTransaction().replace(R.id.ViewPager, fragment).commit;
}
}
HistoryFragment.java
package com.example.calculatorslide;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import java.util.ArrayList;
public class HistoryFragment extends Fragment {
ListView history;
ArrayList<HistoryList> historyLists;
String History="";
View rootView;
public View onCreat(Bundle savedInstanceState){
Bundle bumdle = getArguments();
if (bundle != null)
String value = bundle.getString("key");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final ArrayList<HistoryList> historyLists = new ArrayList<>();
if(History.split("=").length==2){
historyLists.add(new HistoryList(History.split("=")[0],History.split("=")[1]));
}
historyLists.add(new HistoryList("Example", "Example"));
historyLists.add(new HistoryList("23+5", "28"));
HistoryAdapter adapter = new HistoryAdapter(getActivity(), historyLists);
rootView = inflater.inflate(R.layout.fragment_history, container, false);
ListView listView = rootView.findViewById(R.id.history);
listView.setAdapter(adapter);
return rootView;
}
}
here in historyLists taking two parameters for calculation and answer to display in ListView.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
package com.example.android.bloodapp4;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView ourList = findViewById(R.id.theList);
ArrayList<String> list = new ArrayList<>();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(MainActivity.this , android.R.layout.simple_list_item_1,list);
list.add("Account");
list.add("Posts");
list.add("Donations you made");
ourList.setAdapter(arrayAdapter);
ourList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent AccIntent = new Intent(MainActivity.this, AccountActivity.class);
startActivity(AccIntent);
}
});
}
}
Because you don't create ArrayAdapter truly , you must create a TextView in simple_list_item_1 layout and you must add it on ArrayAdapter constructor. Say textview2 is your textview in simple_list_item_1.
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(MainActivity.this , android.R.layout.simple_list_item_1,textview2,list);
That will work I believe.
Have you declared your AccountActivity in AndroidManifest.xml?
A simple example:
<application
....>
<activity
android:name=".AccountActivity"/>
</application>
how to display listview items in android, when a user enter some number in edittext and click on a button to display the specified number of list items on the next activity ?
I have one EditText and a Button on MainActivity1 and a ListView and TextView on MainActivity2. TextView is just for letting me know tht value is passing on next screen.
MainActivity.java
package com.populatelist;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText edt = (EditText)findViewById(R.id.editText1);
Button btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myin = new Intent(MainActivity.this,MainActivity2.class);
myin.putExtra("textbox", edt.getText().toString());
startActivity(myin);
}
});
}
}
MainActivity2.java
package com.populatelist;
import android.support.v7.app.ActionBarActivity;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity2 extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
TextView tv = (TextView)findViewById(R.id.textView1);
Intent myin2 = getIntent();
String str = myin2.getStringExtra("textbox");
tv.setText(str);
final ListView lv = (ListView) findViewById(R.id.listView1);
String[] arrStr = new String[] {
"Hello World",
"Hello India",
"Hello Rajasthan",
"Hello Jodhpur",
"Hello Mujeeb"
};
final List<String> hello_list = new ArrayList<String>(Arrays.asList(arrStr));
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, hello_list);
int n = Integer.parseInt(str);
lv.setAdapter(arrayAdapter);
}
}
You can simply add the coming value at last of your string array like
String[] arrStr = new String[] {
"Hello World",
"Hello India",
"Hello Rajasthan",
"Hello Jodhpur",
"Hello Mujeeb",
str
};
It will show your input value to last position of your listview.
And if you want to add new items and show old as well then you have to pass whole string array to previous activity and add new value to last position, pass it when start next activity. By using this you can see all data on listview.
Whenever you get value in second activity create a new array "b" with required no of values.
String str = myin2.getStringExtra("textbox");
int noOfNames = Integer.parseInt(str);
String[] b = new String[StringnoOfNames];
Then copy the items from the original array
b = Arrays.copyOf(arrStr, noOfNames);
final List<String> hello_list = new ArrayList<String>(Arrays.asList(b));
First, validate if your EditText isn't null, here your app may crash
if (edt.getText().length() > 0) {
Intent myin = new Intent(MainActivity.this,MainActivity2.class);
myin.putExtra("textbox", Integer.parseInt(edt.getText().toString()));
startActivity(myin);
}
Then handle your intent
ListView lv = (ListView) findViewById(R.id.listview1);
ArrayAdapter<String> arrayAdapter = null;
int number = intent.getIntExtra("textbox", 0);
switch (number) {
case 0:
arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, arrStr);
lv.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
break;
case 1:
arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, AnotherSourceArray);
lv.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
break;
case 2:
arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, AnotherSourceArray);
lv.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
break;
...
default:
break;
}
Note - this is just sample. You can resolve this on many another ways. Each switch case may contain another data to display. Using default layouts for listviews may be frustrating, better way is to create custom class which extends ArrayAdapter<String>
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);
I have this mainactivity:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.widget.ArrayAdapter;
import android.widget.ListView;
//Array of options --> ArrayAdapter --> ListView
//List view: {views: list_items.xml}
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
populateListView();
}
private void populateListView() {
//Create list of items
String[] myItems = {"Blue", "Green", "Purple", "Red"};
//Build Adapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this //Context for the activity
R.layout.list_items, //Layout to use (Create)
myItems); //Items to be displayed
//Configure the ListView
ListView list = (ListView) findViewById(R.id.listViewMain);
list.setAdapter(adapter);
ViewPager myViewPager = (ViewPager) findViewById(R.id.viewPager);
myViewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
myViewPager.setCurrentItem(1, false);
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 2: return FirstFragment.newInstance("FirstFragment, Instance 1");
case 1: return SecondFragment.newInstance("SecondFragment, Instance 1");
case 0: return ThirdFragment.newInstance("ThirdFragment, Instance 1");
default: return ThirdFragment.newInstance("ThirdFragment, Default");
}
}
#Override
public int getCount() {
return 3;
}
{}}}
I am trying to add a listview, i have created a xml file called: list_items.xml, but on this line: "R.layout.list_items," i get an error: "layout cannot be resolved or is not a field" and i also get "syntax error on token "R", delete this token". Why is that?
The list_items.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</TextView>
I believe that you misunderstood the constructor for ArrayAdapter.
What you basically need to do is change the R.layout.list_items to a single element layout, just like one you would find in android.R.
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
Here you can see that first parameter is context, second one is single item layout, third (optional) is the ID of the text view you want to target with your collection of strings and the last one is the collection.
You can use your own layouts just like you tried earlier.
If you have any questions I will be happy to answer them, and also supply some code if needed.
It look error in your xml.You can also use the simple list item if you need to display only myItems strings.
String[] myItems = {"Blue", "Green", "Purple", "Red"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, myItems);