When I click in an item of the List the method OnItemClick is not ben called. I'm trying to call another activity to show more information about that "AnaliseEstrutural". What will be in the List is the value Brunton or Clar defined for ehBrunton . Then when the user clicks on a item it will apear the oter information about that "AnaliseEstrutural". But it's not passing by the method.
here is the code:
public class AnalisesPonto extends ListFragment implements OnItemClickListener{
private ArrayList<AnaliseEstrutural> analises;
AnalisesDAO andao;
String idPonto;
private View view;
private ListView analisesList;
private AnalisesAdapter analisesAdapter;
private boolean ehBrunton;
private Intent i;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
idPonto = getArguments().getString("id");
andao = new AnalisesDAO(getActivity().getApplicationContext());
analises = andao.relatorioAnalises(idPonto);
ehBrunton = true;
i = new Intent(getActivity().getApplicationContext(), DadosAnalises.class);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.analises_ponto_layout, null);
analisesList = (ListView) view.findViewById(android.R.id.list);
analisesAdapter = new AnalisesAdapter(getActivity().getApplicationContext(), true);
for (int i = 0; i < analises.size(); i++) {
analisesAdapter.add(analises.get(i));
}
analisesList.setAdapter(analisesAdapter);
ViewGroup parent = (ViewGroup) analisesList.getParent();
parent.removeView(analisesList);
analisesList.setOnItemClickListener(new OnItemClickListener()
{
#Override public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
Bundle extra = new Bundle();
extra.putBoolean("radio", ehBrunton);
extra.putString("tipo_est", analises.get(position).getTipo());
extra.putString("codigo", analises.get(position).getCodigo());
if(ehBrunton) {
extra.putString("brun_clar", analises.get(position).getBrunton());
} else {
extra.putString("brun_clar", analises.get(position).getClar());
}
extra.putString("azimute", analises.get(position).getAzimute());
extra.putString("direcao", analises.get(position).getDirecao());
extra.putString("quadrante", analises.get(position).getQuadrante());
extra.putString("sentido", analises.get(position).getSentido());
extra.putString("descricao",analises.get(position).getDescricao());
extra.putString("mergulho", analises.get(position).getMergulho());
extra.putString("familia", analises.get(position).getFamilia());
i.putExtra("analise", extra);
startActivity(i);
}
});
return analisesList;
}
}
The layout from the List:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="match_parent" >
</ListView>
</LinearLayout>
And here is the Layout of the Element of the List
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/med_angular"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
[RESOLVED] Put the method analisesList.setOnItemClickListener(new OnItemClickListener() inside onActivityCreated instead onCrateView
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
analisesList.setOnItemClickListener(new OnItemClickListener()
{
#Override public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
Bundle extra = new Bundle();
extra.putBoolean("radio", ehBrunton);
extra.putString("tipo_est", analises.get(position).getTipo());
extra.putString("codigo", analises.get(position).getCodigo());
if(ehBrunton) {
extra.putString("brun_clar", analises.get(position).getBrunton());
} else {
extra.putString("brun_clar", analises.get(position).getClar());
}
extra.putString("azimute", analises.get(position).getAzimute());
extra.putString("direcao", analises.get(position).getDirecao());
extra.putString("quadrante", analises.get(position).getQuadrante());
extra.putString("sentido", analises.get(position).getSentido());
extra.putString("descricao",analises.get(position).getDescricao());
extra.putString("mergulho", analises.get(position).getMergulho());
extra.putString("familia", analises.get(position).getFamilia());
i.putExtra("analise", extra);
startActivity(i);
}
});
}
What is this removeView for?
parent.removeView(analisesList);
Also shouldn't you be returning the whole view in onCreateView instead of analisesList?
I guess doing the following fill fix the issues
remove "parent.removeView(analisesList);"
return analisesList;
remove implements onOtemClickListener (You are creating an inner annonymous class as mentioned by Raghunandan)
Related
XML files
Here is the activity_main.xml file. that contains two fragments fragment_list.xml and fragment_deatails.xml
<androidx.fragment.app.FragmentContainerView
android:id="#+id/fragmentContainerView"
android:name="com.udemy.fragmentsapp.ListFrag"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
tools:layout="#layout/fragment_list" />
<androidx.fragment.app.FragmentContainerView
android:id="#+id/fram2"
android:name="com.udemy.fragmentsapp.DetailFrag"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
tools:layout="#layout/fragment_detail" />
Here is the fragment_list.xml file. that contain ListView
<ListView
android:id="#+id/lvList"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Here is the fragment_details.xml file. that contains one TextView
<TextView
android:id="#+id/tvDescription"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/textview"
android:layout_marginTop="20dp"
android:layout_marginRight="20dp"
android:layout_marginLeft="20dp"
android:textSize="18dp"
android:textStyle="bold"
android:textColor="#color/black"/>
Java Files
Here is the ListFrag.java file.
ItemSelected activity;
public interface ItemSelected
{
void onItemSelected(int index);
}
public ListFrag() {
// Required empty public constructor
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
activity = (ItemSelected) context;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ArrayList<String> data = new ArrayList<>();
for (int i = 1; i < 6; i++) {
data.add(i + ". This is item " + i);
}
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1,data));
}
#Override
public void onListItemClick(#NonNull ListView l, #NonNull View v, int position, long id) {
super.onListItemClick(l, v, position, id);
activity.onItemSelected(position);
}
Here is the DeatailFrag.java file.
public DetailFrag(){
super(R.layout.fragment_detail);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_detail, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onAttach(#NonNull Context context) {
super.onAttach(context);
}
Here is the MainActivity.java file. when I want to access the ID "tvDescription" then it's showing ERROR: #layout/activity_main does not contain a declaration with id tvDescription.
Please help me. How can I access the ID? Tell me which one is the way to find IDs.
TextView tvDescription;
ArrayList<String> description;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvDescription = findViewById(R.id.tvDescription);
for (int i = 1; i < 6; i++) {
description.add("Description for item " + i);
}
}
#Override
public void onItemSelected(int index) {
tvDescription.setText(description.get(index));
}
Please run this code in your IDE.
The problem is that your activity and fragment are different classes. And although it is obvious that they represent a single view tree, in fact, in each component class, you should refer to the elements of only its layout.
Thus you need to use
TextView tvDescription = findViewById(R.id.tvDescription);
Directly in the DeatailFrag.onViewCreated after super.onViewCreated
And then, somehow pass the received value back to the activity, if necessary
Happy learning
I set up a Listview in Android Studio but need help with coding a OnItemClickListner.
I have tried the code, but doesn't seem to work.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.list_view);
ArrayList<Object> list = new ArrayList<>();
list.add(new LTCItem("30.06 Sign Violations","Submit A Complaint To Texas Attorney General",R.drawable.gavel));
list.add(new LTCItem("U.S. & Texas LawShield","Legal Defense For Self Defense",R.drawable.lawshield));
listView.setAdapter(new LTCAdapter(this, list));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
});
}
}
Below is my list_view file. Where in the file do block descendantFocusability as suggested? Do I put it under listView? Sorry I am learning .
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:alwaysDrawnWithCache="true"
android:background="#000000"
android:padding="8dp">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ImageView
android:id="#+id/itemListViewImgIcon"
android:layout_width="50dp"
android:layout_height="50dp"
android:contentDescription="#+id/itemListViewImgIcon"
android:src="#mipmap/ic_launcher" />
<TextView
android:id="#+id/itemListViewTxtTopicName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
<TextView
android:id="#+id/itemListViewTxtTopicSubtitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/itemListViewTxtTopicName"
</RelativeLayout>
Ok I added the adapter code which is a Java Class item. Where do I add the code here?
public class LTCAdapter extends BaseAdapter {
ArrayList<Object> list;
private static final int LTC_Item = 0;
private static final int HEADER = 1;
private LayoutInflater inflater;
public LTCAdapter(Context context, ArrayList<Object> list) {
this.list = list;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getItemViewType(int position) {
if (list.get(position) instanceof LTCItem) {
return LTC_Item;
} else {
return HEADER;
}
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return 1;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null) {
switch (getItemViewType(i)) {
case LTC_Item:
view = inflater.inflate(R.layout.item_list_view, null);
break;
case HEADER:
view = inflater.inflate(R.layout.item_listview_header, null);
break;
}
}
switch (getItemViewType(i)) {
case LTC_Item:
ImageView image = (ImageView) view.findViewById(R.id.itemListViewImgIcon);
TextView name = (TextView) view.findViewById(R.id.itemListViewTxtTopicName);
TextView subtitle = (TextView) view.findViewById(R.id.itemListViewTxtTopicSubtitle);
image.setImageResource(((LTCItem) list.get(i)).getImage());
name.setText(((LTCItem) list.get(i)).getName());
subtitle.setText(((LTCItem) list.get(i)).getSubtitle());
break;
case HEADER:
TextView title = (TextView) view.findViewById(R.id.itemListViewHeader);
title.setText(((String) list.get(i)));
break;
}
return view;
}
}
Your ListView element doesn't have an ID, you should add android:id="#+id/list_view" to it in the XML file.
Here is an example:
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
As your list view contains focusable elements, you need to write this piece of code in parent layout in your list view item xml file
android:descendantFocusability="blocksDescendants"
I'm moving my first steps into android, so sorry if this is a stupid question.
I've followed this tutorial to implement a DialogFragment containing a ListView.
This is the ColorDialogFragment.java:
public class ColorDialogFragment extends DialogFragment {
String[] listItems = { "Red", "Blue", "Green"};
ListView myList;
String ipAddress;
public static ColorDialogFragment newInstance(String ipAddress) {
Bundle args = new Bundle();
args.putString("ipAddress",ipAddress);
ColorDialogFragment fragment = new ColorDialogFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ipAddress = getArguments().getString("ipAddress");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_fragment, null, false);
myList = (ListView) view.findViewById(R.id.list);
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, listItems);
myList.setAdapter(adapter);
myList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String colorHex;
switch (i){
case 1:
colorHex = "#FF0000";
break;
case 2:
colorHex = "#0000FF";
break;
case 3:
colorHex = "#00FF00";
break;
default:
dismiss();
return;
}
ClientAsyncTask clientAsyncTask = new ClientAsyncTask(ipAddress, colorHex);
clientAsyncTask.execute();
dismiss();
}
});
}
private class ClientAsyncTask extends AsyncTask<Void, Void, Void> {
...
}
}
And this is dialog_fragment.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</LinearLayout>
</LinearLayout>
The problem is that when I click a list item onItemClick() is not called (and obviously I don't understand why).
I found out by myself that the problem were the wrong indexes in switch statement (starting from 0 and not from 1, obviously).
This question already has answers here:
NullPointerException accessing views in onCreate()
(13 answers)
Closed 8 years ago.
I have just started android app development..and while opening the following app it says "Unfortunately your app has crashed". Can anyone point out the error in this code.
fragmentmain.xml
<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"
android:background="#ffffbb"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="85dp"
android:text="Info of Departments and Student Bodies"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="190dp" >
</ListView>
</LinearLayout>
MainActivity.java
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//adding items to list view
final ListView listview = (ListView) findViewById(R.id.listView);
String values[] = new String[]{"Departments" , "Student_bodies"};
final ArrayList<String> list = new ArrayList<String>();
for (int i=0 ; i < values.length; ++i){
list.add(values[i]);
}
ArrayAdapter<String> ap = new ArrayAdapter<String> (this,android.R.layout.simple_list_item_1,values);
listview.setAdapter(ap);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
if (((TextView)arg1).getText().toString() == "Departments"){
startActivity(new Intent(MainActivity.this,Departments.class));
}
if (((TextView)arg1).getText().toString() == "Student_bodies"){
startActivity(new Intent(MainActivity.this,Student_bodies.class));
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
it is just simple implementation of list view and implementing onClick() on its elements to go to different Activity.thankful if anyone points out mistakes.
Your layout file named FragmentMain but You using activity_main as parameter of setContentView() method. Try to change to setContentView(R.layout.FragmentMain);
Please remove code from onCreate() and added in onCreateView(), as you are using fragment.
And your listview is also define in fragment_main.xml ,
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
final ListView listview = (ListView) rootView.findViewById(R.id.listView);
String values[] = new String[]{"Departments" , "Student_bodies"};
final ArrayList<String> list = new ArrayList<String>();
for (int i=0 ; i < values.length; ++i){
list.add(values[i]);
}
ArrayAdapter<String> ap = new ArrayAdapter<String> (this,android.R.layout.simple_list_item_1,values);
listview.setAdapter(ap);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
if (((TextView)arg1).getText().toString() == "Departments"){
startActivity(new Intent(MainActivity.this,Departments.class));
}
if (((TextView)arg1).getText().toString() == "Student_bodies"){
startActivity(new Intent(MainActivity.this,Student_bodies.class));
}
}
});
return rootView;
}
To make it easier for you to understand, what I'm trying to make is a app which shows me a list of books - name of the book and image of front cover. When clicked on, it will go to another activity, with an enlarged image of the cover and description of the book. It Should be scrollable. This is how much I have.
MainActivity.java
public class MainActivity extends ListActivity {
TextView select;
String[] items = { "Naruto", "One Piece", "Bleach", "Harry Potter", "Vampire's Assistant",
"Pet Cemetery" };
/** Called with the activity is first created. */
#Override
public void onCreate(Bundle a) {
super.onCreate(a);
setContentView(R.layout.activity_main);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items));
select = (TextView) findViewById(R.id.selection);
}
public void onListItemClick(ListView parent, View v, int position, long id) {
select.setText(items[position]);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/selection"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawSelectorOnTop="false"/>
</LinearLayout>
public void onListItemClick(ListView parent, View v, int position, long id) {
Intent i = new Intent(this, ActivityTwo.class);
i.putExtra("book_position", position);
startActivity(i);
}
ActivityTwo(in onCreate or wherever you feel comfortable):
Bundle extras = getIntent().getExtras();
if (extras != null && extras.getInt("book_position", 0) > 0) {
int bookPosition = extras.getInt("book_position");
// Do something with the position. E.g. retrieve the data from the String array in this position and populate a TextView/ImageView
}
public void onListItemClick(ListView parent, View v, int position, long id) {
startActivity(new Intent(getBaseContext(), ActivityToStart.class).putExtra("book", items[position]));
}
Then in ActivityToStart
public class ActivityToStart {
private String bookName;
#Override
public void onCreate(Bundle bundleSavedInstance) {
super.onCreate(bundleSavedInstance);
getIntentExtras();
}
public void getIntentExtras(){
this.bookName = getIntent().getExtra().getString("book");
}
}