Android app crashing on startup [duplicate] - java

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;
}

Related

How To Add Checkboxes To ListView (Each list) in Android Studio

basically I am creating a Task/ToDo List app and I can't figure this part out. I want to add a checkbox next to each task and the ability to check them.
Here is the MainActivity.java
public class MainActivity extends AppCompatActivity {
static ArrayList<String> notes = new ArrayList<>();
static ArrayAdapter arrayAdapter;
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.add_note) {
Intent intent = new Intent(getApplicationContext(),
note_editor.class);
startActivity(intent);
return true;
}
return false;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listView);
SharedPreferences sharedPreferences =
getApplicationContext().getSharedPreferences
("com.example.assignment1", Context.MODE_PRIVATE);
HashSet<String> set = (HashSet<String>)
sharedPreferences.getStringSet("notes", null);
if (set == null) {
notes.add("Add Your Task Hereee");
} else {
notes = new ArrayList(set);
}
arrayAdapter = new ArrayAdapter
(this, android.R.layout.simple_list_item_1, notes);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick
(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(),
note_editor.class);
intent.putExtra("noteId", i);
startActivity(intent);
}
});
My main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:id="#+id/listView" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="32dp"
android:layout_marginBottom="28dp"
android:backgroundTint="#4BB3A9"
android:src="#drawable/add_task"/>
</RelativeLayout>
I want it to look something like this":
I drew the checkboxes here
I also have another class for when editing the tasks as well as for a splash screen but I don't think it's necessary here. Any help would be really appreciated!
You could use Recycler view instead of List view. See below code for Reference:
Create custom adapter and set it to your Recycler view and call it like recyclerView.setAdapter(CustomAdapter(new ArrayList("AAAAA","BBBBB","CCCCC","DDDDD"),getContext()));
Custom Adapter
public class CustomAdapter extends ArrayAdapter<String> {
private ArrayList<String> dataSet;
// View lookup cache
private static class ViewHolder {
CheckedTextView checkedTextView;
}
public CustomAdapter(ArrayList<String> data, Context context) {
super(context, R.layout.list_item, data);
this.dataSet = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.list_item, parent, false);
viewHolder.checkedTextView = convertView.findViewById(R.id.check_box);
viewHolder.checkedTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewHolder.checkedTextView.setChecked(!viewHolder.checkedTextView.isChecked());
}
});
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.checkedTextView.setText(dataSet.get(position));
return convertView;
}
}
XML code for each list item : list_item.xml
<CheckedTextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/check_box"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
android:checked="false"
android:checkMark="?android:attr/listChoiceIndicatorMultiple"
android:gravity="center"
android:text="Check Me"
/>
You are using an android default layout for your ListView and this default layout shows a TextView only, you have to create custom layout for your list item views and custom ArrayAdapter to achieve what you want.
for more information check out this:https://javapapers.com/android/android-listview-custom-layout-tutorial/
As a tip switch for RecyclerView which is much more efficient: https://developer.android.com/guide/topics/ui/layout/recyclerview

Android Search ListView

i am using the ListView method to search in a custom listview. I have made an image and textview as elements to search. However, the edittext in which i used as the search bar cant properly filter my items but when tested using only text it works. Is there a way that my codes could be corrected? it doesn't show any errors. The Image Shown shows that when i try to filter T it doesn't show temasek ;instead it shows only the first two elements.
MainActivity.java:
public class MainActivity extends Activity {
String[] schools = { "Elias Park Primary",
"Anderson Secondary",
"Temasek JC",
"Republic Poly",
"Nanyang Poly" ,
"Meridian JC",
"Temasek Poly",
"Ngee Ann Poly",
"Anglican High"
};
Integer[] imageId = {
R.drawable.eliaspark_pri,
R.drawable.anderson_sec,
R.drawable.temasek_jc,
R.drawable.republic_poly,
R.drawable.nyp,
R.drawable.mjc,
R.drawable.tp,
R.drawable.ngee_ann,
R.drawable.anglican_high
};
ListView list;
custom adapter1;
EditText inputSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView)findViewById(R.id.list);
inputSearch = (EditText) findViewById(R.id.inputSearch);
adapter1 = new custom(MainActivity.this, schools, imageId);
list.setAdapter(adapter1);
inputSearch.addTextChangedListener(new TextWatcher(){
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
Log.i("Char Sqequence", ""+s);
MainActivity.this.adapter1.getFilter().filter(s);
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
}
#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);
}}
Custom Listview :
public class custom extends ArrayAdapter<String>{
private final Activity context ;
private final String[] schools ;
private final Integer[] imageId;
public custom(Activity context, String[] schools, Integer[] imageId){
super(context, R.layout.list1,schools);
this.context = context;
this.schools = schools;
this.imageId = imageId;
}
public View getView(int position, View view, ViewGroup parent){
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.list1,null,true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
txtTitle.setText(schools[position]);
imageView.setImageResource(imageId[position]);
return rowView;
}}
XML Listview :
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
</ListView>
Custom ListView :
<?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/txt"
android:layout_width="wrap_content"
android:layout_height="match_parent"
/>
<ImageView
android:id="#+id/img"
android:layout_width="50dp"
android:layout_height="match_parent"
/>

TextView is null after setContentView

I've looked at several similar questions on here, but none of them have explained my problem. I am simply trying to reference a TextView by it's id, but I keep getting Null Pointer Exceptions whenever I try to do anything with it. I made sure to put my assignment after both setContentView() is called and the fragment is inflated. To make sure there wasn't anything else causing problem I removed the other portions of my code and tested for null immediately after assignment. Regardless of this, it's still showing as null.
Here's my code:
public class MainActivity extends Activity
{
//MEMBER VARIABLES
TextView mQuestionText;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null)
{
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
mQuestionText = (TextView) findViewById(R.id.questionTextView);
if (mQuestionText == null)
System.out.println("debug:: " + "null");
}
#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;
}
}
}
And here's the fragment_main.xml:
<RelativeLayout 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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="edu.wichita.eecs.cs697ac.w387u669.assignment3.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/questionTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="41dp"
android:text="Question"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/button1"
android:layout_toRightOf="#+id/questionTextView"
android:text="False" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/questionTextView"
android:layout_marginTop="35dp"
android:layout_toLeftOf="#+id/questionTextView"
android:text="True" />
</RelativeLayout>
Thanks for your help!
EDIT: After doing some other research, I learned that I could override the onStart() method and move my code there as I would have access to the views (even those from the fragment). However this is just a bypass that doesn't really use fragments as they are meant to be used.
protected void onStart()
{
super.onStart();
TextView test = (TextView) findViewById(R.id.questionTextView);
test.setText("hello");
}
Hope that helps someone
questionTextView TextView is in fragment_main.xml layout of PlaceholderFragment, so use onCreateView of Fragment to initialize TextView as:
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
TextView mQuestionText = (TextView)rootView.findViewById(R.id.questionTextView);
if your using Fragment you shoud reference it from the fragment OnCreateView method
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null)
{
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#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);
TextView QuestionText = (TextView) rootView.findViewById(R.id.questionTextView);
if (mQuestionText == null)
System.out.println("debug:: " + "null");
return rootView;
}
} }
You have set setContentView(R.layout.activity_main) but your xml name is fragment_main.xml
Use this XML in setContentView i.e. setContentView(R.layout.fragment_main)

Add Items to ListView - Android

This is my first experience with android. I'm trying to add items to my ListView.
I use Tabs, and the only way to see that the item was added is to change tab and then come back to the first tab.
I searched around, and I've always found
adapter.notifyDataSetChanged();
but doesn't work for me.
I have created the project with, as I said, Fixed Tabs + Swipe.
I simply want to have listviews which rows have an EditText, a Spinner and a Button.
On the bottom of the Fragment used for the tab, I have an ImageButton. I want to click on it and have a new Row.
my custom Adapter:
package com.andreapivetta.uconverter;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
public class CustomAdapter extends ArrayAdapter<String> {
private final Context context;
private final int resourceID;
public CustomAdapter(Context context, int resource, ArrayList<String> bah) {
super(context, resource, bah);
this.context = context;
this.resourceID = resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(resourceID, parent, false);
return rowView;
}
}
fragment_main_dummy.xml
<RelativeLayout 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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity$DummySectionFragment" >
<ListView
android:id="#+id/unitListView"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<ImageButton
android:id="#+id/moreImageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:contentDescription="#string/image_button_delete"
android:src="#android:drawable/ic_input_add" />
</RelativeLayout>
Row.xml
<?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">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
<EditText
android:id="#+id/unitEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView1"
android:ems="10"
android:inputType="numberDecimal" >
<requestFocus />
</EditText>
<Spinner
android:id="#+id/unitSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageButton1"
android:layout_marginBottom="15dp"
android:layout_toRightOf="#+id/unitEditText" />
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/unitEditText"
android:layout_alignParentRight="true"
android:onClick="removeItem"
android:contentDescription="#string/image_button_delete"
android:src="#android:drawable/ic_menu_delete" />
</RelativeLayout>
MainActivity...
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#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 void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 4 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
case 3:
return getString(R.string.title_section4).toUpperCase(l);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
ArrayList<String> myStringArray1 = new ArrayList<String>();//new String[]{"Egzo","Eg","Egzona"};
String[] myStringArray2 = new String[]{"aaa","bbb","ccc"};
String[] myStringArray3 = new String[]{"ddd","eeee"};
String[] myStringArray4 = new String[]{"Cia","ci","Ciao"};
public static ArrayAdapter<String> adapter;
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy,container, false);
//TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
//dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
// ListView
ListView unitListView = (ListView) rootView.findViewById(R.id.unitListView);
switch(getArguments().getInt(ARG_SECTION_NUMBER)) {
case 1:
myStringArray1.add("mmm");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
unitListView.setAdapter(adapter);
break;
case 2:
adapter = new ArrayAdapter<String>(getActivity(), R.layout.row, R.id.textView1, myStringArray2);
unitListView.setAdapter(adapter);
break;
case 3:
adapter = new ArrayAdapter<String>(getActivity(), R.layout.row, R.id.textView1, myStringArray3);
unitListView.setAdapter(adapter);
break;
case 4:
adapter = new ArrayAdapter<String>(getActivity(), R.layout.row, R.id.textView1, myStringArray4);
unitListView.setAdapter(adapter);
break;
}
unitListView.setOnItemClickListener(listViewOnClickListener);
// ImageButton
ImageButton moreImageButton = (ImageButton) rootView.findViewById(R.id.moreImageButton);
moreImageButton.setOnClickListener(moreListener);
return rootView;
}
public OnClickListener moreListener = new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
myStringArray1.add("Andrea");
adapter.clear();
adapter.addAll(myStringArray1);
adapter.notifyDataSetChanged();
}
};
public OnItemClickListener listViewOnClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
};
}
}
Note that I'm working only with the first tab right now...
What am I doing wrong? :)
ListView myListView = (ListView) rootView.findViewById(R.id.myListView);
ArrayList<String> myStringArray1 = new ArrayList<String>();
myStringArray1.add("something");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
myListView.setAdapter(adapter);
Try it like this
public OnClickListener moreListener = new OnClickListener() {
#Override
public void onClick(View v) {
adapter = null;
myStringArray1.add("Andrea");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
myListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
};
Try this one it will work
public class Third extends ListActivity {
private ArrayAdapter<String> adapter;
private List<String> liste;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };
liste = new ArrayList<String>();
Collections.addAll(liste, values);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, liste);
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
liste.add("Nokia");
adapter.notifyDataSetChanged();
}
}
public OnClickListener moreListener = new OnClickListener() {
#Override
public void onClick(View v) {
adapter.add("aaaa")
}
}

OnItemClick not being called in List Fragment

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)

Categories

Resources