Android - Listview in Fragment - java

I want to create a ListView in Fragment but something goes wrong.
In layout listmygroups.xml are three TextViews (trainermygroupslistwhen, trainermygroupslistwhere, trainermygroupslistname).
I try to open fragment with listview(TrainerMyGroups) from another fragment by:
getFragmentManager().beginTransaction().replace(R.id.MainContainer,new TrainerMyGroups()).addToBackStack(null).commit();
TrainerMyGroups.java:
package com.hgyghyfghyu.apkana40;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
/**
* A simple {#link Fragment} subclass.
*/
public class TrainerMyGroups extends Fragment {
ListView listView;
TrainerGroupsAdapter adapter;
String when[]={"tak","ret","sd"};
String where[]={"dsf","sdf","sdfsdf"};
String name[]={"sdfsdf","xcvxcv","xcvxcv"};
public TrainerMyGroups() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_trainer_my_groups, container, false);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listView = (ListView) getActivity().findViewById(R.id.trainermygroupslistview);
adapter = new TrainerGroupsAdapter(getContext(),R.layout.list_mygroups);
for(int i=0;i<3;i++){
TrainerGroupsDataProvider dataprovider = new TrainerGroupsDataProvider(when[i],name[i],where[i]);
adapter.add(dataprovider);
}
listView.setAdapter(adapter);
}
}
TrainerGroupsAdapter.java:
package com.hgyghyfghyu.apkana40;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
import java.util.ArrayList;
/**
* Created by dd on 2016-04-04.
*/
public class TrainerGroupsAdapter extends ArrayAdapter {
List list = new ArrayList();
public TrainerGroupsAdapter(Context context, int resource) {
super(context, resource);
}
static class Datahandler{
TextView name;
TextView when;
TextView where;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return this.list.size();
}
#Override
public Object getItem(int position) {
return this.list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row=convertView;
Datahandler handler;
if(convertView==null){
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row= inflater.inflate(R.layout.list_mygroups,parent,false);
handler = new Datahandler();
handler.name = (TextView) row.findViewById(R.id.trainermygroupslistname);
handler.where = (TextView) row.findViewById(R.id.trainermygroupslistwhere);
handler.when = (TextView) row.findViewById(R.id.trainermygroupslistwhen);
row.setTag(handler);
}
else {
handler = (Datahandler)row.getTag();
}
TrainerGroupsDataProvider dataProvider;
dataProvider = (TrainerGroupsDataProvider)this.getItem(position);
handler.name.setText(dataProvider.getName());
handler.when.setText(dataProvider.getWhen());
handler.where.setText(dataProvider.getWhere());
return row;
}
}
and there is error from AndroidMonitor
FATAL EXCEPTION: main
Process: com.hgyghyfghyu.apkana40, PID: 27778
java.lang.NullPointerException
at com.hgyghyfghyu.apkana40.TrainerMyGroups.onCreate(TrainerMyGroups.java:41)
at android.support.v4.app.Fragment.performCreate(Fragment.java:1951)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1029)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5045)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
line 41 from TrainerMyGroups is
listView.setAdapter(adapter);
I am not sure but probably this solution works only in Activity, not in Fragment, How can I change my code to make it workable?
element list 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="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="5">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/trainermygroupslistwhen"
android:textStyle="bold"
android:textSize="20sp"
android:textColor="#FFFFFF"
android:layout_centerInParent="true"/>
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="3">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/trainermygroupslistname"
android:textStyle="bold"
android:textSize="10sp"
android:textColor="#FFFFFF"
android:layout_centerInParent="true"/>
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="3">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/trainermygroupslistwhere"
android:textStyle="bold"
android:textSize="10sp"
android:textColor="#FFFFFF"
android:layout_centerInParent="true"/>
</RelativeLayout>
</LinearLayout>
</LinearLayout>

You should add some data before set the adapter:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listView = (ListView) getActivity().findViewById(R.id.trainermygroupslistview);
adapter = new TrainerGroupsAdapter(getContext(),R.layout.list_mygroups);
for(int i=0;i<3;i++){
TrainerGroupsDataProvider dataprovider = new TrainerGroupsDataProvider(when[i],name[i],where[i]);
adapter.add(dataprovider);
}
listView.setAdapter(adapter);
}

Related

Android Studio Grid View doesn't show when I run the app

I created a Java class that should display something like this:
But this is what I get when I run the app:
It doesn't show what I wanted and Android Studio doesn't show any error in Logcat, so I don't know why it's not working.
This is the code for the class SetsActivity:
package com.example.myquiz;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.GridView;
import android.widget.Toolbar;
public class SetsActivity extends AppCompatActivity {
private GridView sets_grid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sets);
androidx.appcompat.widget.Toolbar toolbar = findViewById(R.id.set_toolbar);
//setSupportActionBar(toolbar);
String title = getIntent().getStringExtra("CATEGORY");
getSupportActionBar().setTitle(title);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
sets_grid = findViewById(R.id.sets_gridview);
SetsAdapter adapter = new SetsAdapter(2);
sets_grid.setAdapter(adapter);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId() == android.R.id.home)
{
SetsActivity.this.finish();
}
return super.onOptionsItemSelected(item);
}
}
I also created an adapter class SetsAdapter so I'm gonna post the code for it as well:
package com.example.myquiz;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class SetsAdapter extends BaseAdapter {
private int numOfSets;
public SetsAdapter(int numOfSets) {
this.numOfSets = numOfSets;
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.set_item_layout, parent, false);
} else {
view = convertView;
}
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(parent.getContext(),QuestionActivity.class);
parent.getContext().startActivity(intent);
}
});
((TextView) view.findViewById(R.id.setNo_tv)).setText(String.valueOf(position + 1));
return view;
}
}
And here is the code for the XML file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".SetsActivity"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:id="#+id/set_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark"
></androidx.appcompat.widget.Toolbar>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sets"
android:textSize="26sp"
android:textStyle="bold"
android:padding="16dp" />
<GridView
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="#+id/sets_gridview"
android:layout_weight="1"
android:gravity="center"
android:horizontalSpacing="16dp"
android:verticalSpacing="16dp"
android:padding="16dp"
android:columnWidth="100dp"
android:numColumns="auto_fit"
></GridView>
</LinearLayout>
Here is the code for the XML file set_item_layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="100dp"
android:layout_height="100dp"
android:orientation="vertical"
android:gravity="center"
android:background="#drawable/round_corner"
android:backgroundTint="#FFC3C3"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:id="#+id/setNo_tv"
android:textStyle="bold"
android:textColor="#android:color/black"
android:textSize="45sp"></TextView>
</LinearLayout>
The getCount() method in the SetsAdapter should return numOfSets not 0.
#Override
public int getCount() {
return numOfSets;
}

How to add the ListView element to be referenced in the individual Activity files

The app crashes as soon as any of the list Activities are launched:
NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter' on a null object reference
My instructor says its happening because the layouts haven't been configured correctly. Right now, the list_item is being inflated as the Activity layout. Please create a separate layout, such as activity_list and add the ListView element there to be referenced in the individual Activity files
Here's the code
MainActivity
package com.example.tourguide;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button event = (Button) findViewById(R.id.events);
Button mall = (Button) findViewById(R.id.malls);
Button resturant = (Button) findViewById(R.id.resturants);
Button university = (Button) findViewById(R.id.uinversities);
event.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent event = new Intent(MainActivity.this, events.class);
startActivity(event); }
});
mall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mall = new Intent(MainActivity.this, malls.class);
startActivity(mall);
}
});
resturant.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent resturant = new Intent(MainActivity.this, resturants.class);
startActivity(resturant);
}
});
university.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent university = new Intent(MainActivity.this, universities.class);
startActivity(university);
}
});
}}
WordAdapter.java
package com.example.tourguide;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class WordAdapter extends ArrayAdapter<listitem> {
public WordAdapter(Activity context, ArrayList<listitem> listitems) {
super(context, 0, listitems);
}
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if(listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
listitem currentItem = getItem(position);
TextView name = (TextView) listItemView.findViewById(R.id.text1);
name.setText(currentItem.getName());
ImageView image = (ImageView) listItemView.findViewById(R.id.image1);
image.setImageResource(currentItem.getImage());
TextView dist = (TextView) listItemView.findViewById(R.id.text2);
dist.setText(currentItem.getDist());
TextView price = (TextView) listItemView.findViewById(R.id.text2);
price.setText(currentItem.getPrice());
return listItemView;
}
}
listitem.java
package com.example.tourguide;
import android.widget.ImageView;
public class listitem {
private String name="";
private int image;
private String dist="";
private String price="";
public listitem(String namea, int imagea, String dista, String pricea){
name = namea;
imagea = image;
dist= dista;
price=pricea;
}
/*********** Set Methods ******************/
public void setName(String name)
{
this.name = name;
}
public void setImage(int image)
{
this.image = image;
}
public void setDist(String dist)
{
this.dist = dist;
}
public void setPrice(String price)
{
this.price = price;
}
/*********** Get Methods ****************/
public String getName()
{
return this.name;
}
public int getImage()
{
return this.image;
}
public String getDist()
{
return this.dist;
}
public String getPrice()
{
return this.price;
}
}
Univerisities.java
package com.example.tourguide;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.ListView;
import java.util.ArrayList;
public class universities extends Activity {
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.list_item);
ArrayList<listitem> listitemArrayList = new ArrayList<listitem>();
listitemArrayList.add(new listitem("Prince Sultan University", R.drawable.u1, "AlNarjes Dist", "$"));
listitemArrayList.add(new listitem("Princess Nourah University", R.drawable.u2, "AlNarjes Dist", "$"));
listitemArrayList.add(new listitem("King Saud University", R.drawable.u3, "AlNarjes Dist", "$"));
WordAdapter adapter = new WordAdapter(this, listitemArrayList);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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"
tools:context="com.example.tourguide.MainActivity"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="29sp"
android:textColor="#3DC195"
android:textAlignment="center"
android:text="Tour Guide App" />
<TextView
android:id="#+id/text2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#6AA13F"
android:textSize="18sp"
android:text="Tour Guide App is designed to help you discover Riyadh city sightseeings including events, malls, resturants and universities.the app will be developed periodically to add more features... stay tuned" />
<Button
android:id="#+id/events"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Events"
android:onClick="onClickEvent"/>
<Button
android:id="#+id/malls"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Malls"
android:onClick="onClickMall"/>
<Button
android:id="#+id/resturants"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Resturants"
android:onClick="onClickRest"/>
<Button
android:id="#+id/uinversities"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Universities"
android:onClick="onClickUniv"/>
</LinearLayout>
activity_list.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">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
list_item.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
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/image1"
android:layout_width="163dp"
android:layout_height="96dp"
android:layout_marginLeft="15dp"
android:layout_marginTop="15dp"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="68dp"
android:layout_marginTop="30dp"
android:orientation="vertical">
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#DB0BA4"
android:textSize="20sp"
/>
<TextView
android:id="#+id/text2"
android:layout_width="113dp"
android:layout_height="wrap_content"
android:textColor="#456233"
android:textSize="15sp"
/>
<TextView
android:id="#+id/text3"
android:layout_width="113dp"
android:layout_height="wrap_content"
android:textColor="#C1B03D"
android:textSize="15sp"
/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
In the file Univerisities.java you should change your layout file to activity_list.xml.
Line
setContentView(R.layout.list_item);
Must be changed to :
setContentView(R.layout.activity_list);
Bro,
First you are trying to inflate the ListView item into you activity, which is wrong:
Change the setContentView(R.layout.list_item) to setContentView(R.layout.activity_list);
Also please check out the ViewHolder pattern for ListView's since the your adapter's getView method should be improved by that to make scrolling even more smooth:
View listItemView = convertView;
if(listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
and if no items are appearing in the list, you should also override the getItemCount on adatpterto return the size of the list.

How to move to next activtity with bundle the touch event is not working

guys in my project i need to click the item on the list and move to next activity using bundle i need to carry some data also, but i have some issue..
Please help me to move to next activity i can't understand what is the mistake i did,when i click on the item it is not even responding..
here i just use "e_name.setText("hiiii")" for testing purpose its not working.
AT THE END I HAVE MENTIONED MY LAYOUT CODES ALSO.
if possible please send me a link to learn more about custom adapter and list view..
//Main activity.java
package com.prematix.ashok.friday_9;
import android.app.ListActivity;
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.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
EditText e_name, e_desig, e_salary;
Button save;
String itemNames[];
String itemDescriptions[];
ListView itemsListView;
ArrayList<Item> list = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e_name = (EditText) findViewById(R.id.ed_name);
e_desig = (EditText) findViewById(R.id.ed_desig);
e_salary = (EditText) findViewById(R.id.ed_salary);
save = (Button) findViewById(R.id.save);
itemsListView = (ListView) findViewById(R.id.mylist);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//create adapter object
CustomListAdapter adapter = new CustomListAdapter(getApplicationContext(), generateItemsList());
//set custom adapter as adapter to our list view
itemsListView.setAdapter(adapter);
}
private ArrayList<Item> generateItemsList() {
itemNames = new String[]{e_name.getText().toString()};
itemDescriptions = new String[]{e_desig.getText().toString()};
for (int i = 0; i < itemNames.length; i++) {
list.add(new Item(itemNames[i], itemDescriptions[i]));
}
return list;
}
});
itemsListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
e_name.setText("hiiiii");
}
});
// ListView itemsListView = (ListView)findViewById(R.id.list_view_items);
}
}
//CustommListAdapter.java
package com.prematix.ashok.friday_9;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by ${Nagaveni} on 2017-06-09.
*/
public class CustomListAdapter extends BaseAdapter {
private Context context;
private ArrayList<Item> items;
public CustomListAdapter(Context context,ArrayList<Item> items){
this.context = context;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int i) {
return items.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if(view == null) {
view = LayoutInflater.from(context).inflate(R.layout.layout_list_view_row_items, viewGroup, false);
}
//get current item to be displayed
Item currentitem = (Item)getItem(i);
//get the text view for item name and item designation
TextView name = (TextView)view.findViewById(R.id.name);
TextView designation = (TextView)view.findViewById(R.id.desig);
TextView salary = (TextView)view.findViewById(R.id.salary);
//sets the text for item name and item designation from the current item object
name.setText(currentitem.getNames());
designation.setText(currentitem.getDesignation());
salary.setText("10,000");
//returns the view for current row
return view;
}
}
//here is my layout code
layout_list_view_items.xml
<?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="wrap_content">
<LinearLayout
android:layout_width="260dp"
android:layout_marginLeft="8dp"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="name"
android:id="#+id/name"
android:textStyle="bold"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="designation"
android:id="#+id/desig"
android:textStyle="bold"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="salary"
android:id="#+id/salary"
android:textStyle="bold"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginLeft="70dp">
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/checkBox"
android:layout_weight="1" />
</LinearLayout>
</LinearLayout>
//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:id="#+id/activity_main"
android:orientation="vertical"
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="com.prematix.ashok.friday_9.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="Name"
android:ems="10"
android:id="#+id/ed_name" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="Designation"
android:ems="10"
android:id="#+id/ed_desig" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="Salary"
android:ems="10"
android:id="#+id/ed_salary" />
<Button
android:text="Save"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/save" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/mylist"/>
</LinearLayout>

Getting error in Counter in Android

Following is my code. I need to get the increment value in FloatingActionButton. I've written the code.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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="database.fab.MainActivity">
<ListView
android:id="#+id/lvListView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rel1" >
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/rlRelativeLayout"
android:layout_margin="16dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" >
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="65dp"
android:layout_height="65dp"
android:layout_gravity="bottom|end"
android:src="#mipmap/cart_main"
android:clickable="true"
android:scaleType="fitXY"
android:onClick="fab" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/null_value_zero"
android:id="#+id/fab_text"
android:textColor="#42b138"
android:layout_marginTop="23dp"
android:layout_centerHorizontal="true"
android:textStyle="bold"
android:textSize="17sp"
android:elevation="7dp" />
</RelativeLayout>
</RelativeLayout>
</RelativeLayout>
custom_listview.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_margin="16dp"
android:background="#FFFFFF"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="140dp">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginStart="20dp"
android:layout_marginLeft="20dp"
android:layout_centerVertical="true"
android:id="#+id/ivImageViewMain"/>
<ImageView
android:layout_width="120dp"
android:layout_height="80dp"
android:id="#+id/CounterImage"
android:src="#mipmap/main_add"
android:layout_marginRight="20dp"
android:layout_marginEnd="20dp"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
</RelativeLayout>
</RelativeLayout>
MainActivity.java
package database.fab;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
ListView lvListView;
ImageView CounterImage;
TextView fab_text;
Adapter adapter;
int counter = 0;
int[] images_item = {
R.mipmap.apple,
R.mipmap.blackberry,
R.mipmap.cherry,
R.mipmap.coconut,
R.mipmap.grapes,
R.mipmap.orange,
R.mipmap.peach,
R.mipmap.pineapple,
R.mipmap.pomegranate,
R.mipmap.banana
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvListView = (ListView) findViewById(R.id.lvListView);
fab_text = (TextView) findViewById(R.id.fab_text);
ImageView imageView= (ImageView) findViewById(R.id.CounterImage);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter++;
fab_text.setText(String.valueOf(counter));
}
});
adapter = new Adapter(getApplicationContext(), R.layout.custom_listview);
lvListView.setAdapter(adapter);
int i = 0;
for (int Image : images_item){
Helper helper = new Helper(images_item[i]);
adapter.add(helper);
i++;
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
}
}
Adapter.java
package database.fab;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.List;
public class Adapter extends ArrayAdapter {
List arrayList = new ArrayList();
public Adapter(Context context, int resource) {
super(context, resource);
}
int counter;
public void add(Helper object) {
super.add(object);
arrayList.add(object);
}
static class ImageHolder{
ImageView img_item;
}
#Override
public int getCount() {
return this.arrayList.size();
}
#Override
public Object getItem(int position) {
return this.arrayList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
view = convertView;
ImageHolder imageHolder;
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.custom_listview, parent, false);
imageHolder = new ImageHolder();
imageHolder.img_item = (ImageView) view.findViewById(R.id.ivImageViewMain);
view.setTag(imageHolder);
}
else {
imageHolder = (ImageHolder) view.getTag();
}
Helper h;
h = (Helper) this.getItem(position);
imageHolder.img_item.setImageResource(h.getImage_item());
return (view);
}
}
Helper.java
package database.fab;
public class Helper {
private int image_item;
public Helper(int image_item) {
this.image_item = image_item;
}
public int getImage_item() {
return image_item;
}
public void setImage_item(int image_item) {
this.image_item = image_item;
}
}
Error
12-21 13:01:00.535 13336-13336/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: database.fab, PID: 13336
java.lang.RuntimeException: Unable to start activity ComponentInfo{database.fab/database.fab.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2308)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2368)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1285)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5233)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at database.fab.MainActivity.onCreate(MainActivity.java:42)
at android.app.Activity.performCreate(Activity.java:6001)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2368) 
at android.app.ActivityThread.access$800(ActivityThread.java:144) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1285) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5233) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693) 
I need to get the increment value in FloatingActionButton after I press the add image. Don't know where I went wrong. Please help me with this. Thanks in advance.
Update: revert this, I missed the second ImageView - sry
change this:
ImageView imageView= (ImageView) findViewById(R.id.CounterImage);
to:
ImageView imageView= (ImageView) findViewById(R.id.ivImageViewMain);
Update:
In your main activity you are setting the view to activity_main.xml:
setContentView(R.layout.activity_main);
Then you are trying to get the view with the ID CounterImage:
ImageView imageView = (ImageView) findViewById(R.id.CounterImage)
which does not exist in activity_main.xml
Update 2:
You should look at a few Java and Android basics.
int i = 0;
for (int Image : images_item){
Helper helper = new Helper(images_item[i]);
adapter.add(helper);
i++;
}
You are mixing two for-loops here.
This:
for(int image : images_item) {
adapter.add(new Helper(image));
}
would be a nicer way to do the same thing.
Update 3:
You are inflating the correct layout in Adapter.java:
view = layoutInflater.inflate(R.layout.custom_listview, parent, false);
Right there you can add a OnClickListener:
ImageView imageView= (ImageView) view.findViewById(R.id.CounterImage);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter++;
fab_text.setText(String.valueOf(counter));
}
});
Don't forget to remove the false code from the Activity.

android fragments problems

i wrote a toDO list for my android class. It totally works , but now i want to display the todo list on a fragment ( so it can be its on tab). but when i tried making the fragment , i get a weird error when i try to run it. apparently the error comes from my main activity . so the way i have it set up is that, my main activity has a button that opens the fragment that has all the TOdolist stuff in it. but when i run it on my phone i get a unfortunately TodoList ha stopped as soon as it runs. the error is get is
06-10 22:21:51.284 5302-5302/com.example.mike.todolist D/AbsListView﹕ Get MotionRecognitionManager
06-10 22:21:51.304 5302-5302/com.example.mike.todolist D/AndroidRuntime﹕ Shutting down VM
06-10 22:21:51.304 5302-5302/com.example.mike.todolist W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x417c2898)
06-10 22:21:51.314 5302-5302/com.example.mike.todolist E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.mike.todolist.ToDoFragment.onCreateView(ToDoFragment.java:38)
at android.app.Fragment.performCreateView(Fragment.java:1699)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:903)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1075)
at android.app.BackStackRecord.run(BackStackRecord.java:682)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1455)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:441)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5455)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
at dalvik.system.NativeStart.main(Native Method)
my main activity look like
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.view.View;
public class MainActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.todo_main_activity);
super.onCreate(savedInstanceState);
Button button1 = (Button) findViewById(R.id.fragButton);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction
=fragmentTransaction=fragmentManager.beginTransaction();
ToDoFragment fragment = new ToDoFragment();
fragmentTransaction.add(R.id.mainLL, fragment);
fragmentTransaction.commit();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return true;
}
}
My main activity xml is
<?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:id="#+id/mainLL"
android:layout_height="fill_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="frag"
android:id="#+id/fragButton"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:onClick="fragButtonClick"
android:layout_gravity="center_horizontal" />
</LinearLayout>
Fragment.java
package com.example.mike.todolist;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ListFragment;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import com.example.mike.todolist.db.Contract;
import com.example.mike.todolist.db.DBHelper;
/**
* Created by mike on 6/10/15.
*/
public class ToDoFragment extends ListFragment {
public ListAdapter listAdapter;
public DBHelper helper;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view=inflater.inflate(R.layout.fragmentlayout, container, false);
// Inflate the layout for this fragment
update();
Button doneButton = (Button)view.findViewById(R.id.doneButton);
doneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
View v = (View) view.getParent();
TextView taskTextView = (TextView) v.findViewById(R.id.taskTextView);
String task = taskTextView.getText().toString();
String sql = String.format("DELETE FROM %s WHERE %s = '%s'",
Contract.TABLE_NAME,
Contract.Columns.TASK,
task);
helper = new DBHelper(getActivity());
SQLiteDatabase sqlDB = helper.getWritableDatabase();
sqlDB.execSQL(sql);
update();
}
});
Button addButton = (Button)view.findViewById(R.id.AddButton);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
switch (R.id.add_task) {
case R.id.add_task:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Add a task");
builder.setMessage("What would you like to do?");
final EditText input = new EditText(getActivity());
builder.setView(input);
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String task = input.getText().toString();
helper = new DBHelper(getActivity());
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.clear();
cv.put(Contract.Columns.TASK, task);
db.insertWithOnConflict(Contract.TABLE_NAME, null, cv, SQLiteDatabase.CONFLICT_IGNORE);
update();
}
});
builder.setNegativeButton("Cancel", null);
builder.create().show();
}
}
});
return view;
}
private void update() {
helper = new DBHelper(getActivity());
SQLiteDatabase sqlDB = helper.getReadableDatabase();
Cursor cursor = sqlDB.query(Contract.TABLE_NAME,
new String[]{Contract.Columns._ID, Contract.Columns.TASK},
null, null, null, null, null);
listAdapter = new SimpleCursorAdapter(
getActivity(),
R.layout.task_view,
cursor,
new String[]{Contract.Columns.TASK},
new int[]{R.id.taskTextView},
0
);
this.setListAdapter(listAdapter);
}
}
and this is my fragmentlayout
<?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:id="#+id/mainLL"
android:layout_height="fill_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#android:id/list"
android:layout_weight="1"
android:layout_margin="5dp"
android:background="#color/grey"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Task"
android:id="#+id/AddButton"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:onClick="AddButtonClick"
android:layout_gravity="center_horizontal" />
</LinearLayout>
taskview
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/taskTextView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="20dp"
android:textColor="#color/black"
android:typeface="sans"
android:layout_toLeftOf="#+id/doneButton"
android:layout_alignBottom="#+id/doneButton"
android:gravity="center_vertical"
android:textStyle="bold"
android:layout_alignTop="#+id/doneButton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Done"
android:id="#+id/doneButton"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:onClick="DoneButtonClick"
/>
</RelativeLayout>
According to android developers official website (HERE)
ListActivity has a default layout that consists of a single, full-screen list in the center of the screen. However, if you desire, you can customize the screen layout by setting your own view layout with setContentView() in onCreate(). To do this, your own view MUST contain a ListView object with the id "#android:id/list" (or list if it's in code)
for example:
<?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"
android:paddingLeft="8dp"
android:paddingRight="8dp">
<ListView android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00FF00"
android:layout_weight="1"
android:drawSelectorOnTop="false"/>
<TextView android:id="#android:id/empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF0000"
android:text="No data"/>
</LinearLayout>
So either add a listview to your list activity xml or if you don't need a list view in your activity then simply use FragmentActivity to hold fragments.There is no point in using ListActivity unless it holds a ListView.
Your class is extending to a ListActivity which requires the ListView element in the xml. Your purpose be best served by extending your MainActivity class to Activity and fragments (if any) to Fragments class....
Add an list view to your xml with id android.R.id.list
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
add this xml to your layout
use Activity or FragmentActivity instead of ListActivity
if you want to use ListActivity see here once. you can use ListActivity without setting content view (setContentView()). you can directly setAdapter. or else use your own layout having one ListView with id as "#android:id/list"
EDIT :
public void onClick(View arg0) {
TextView taskTextView = (TextView) view.findViewById(R.id.taskTextView);//directly use 'view' if 'R.id.taskTextView'it present in 'view'
String task = taskTextView.getText().toString();
String sql = String.format("DELETE FROM %s WHERE %s = '%s'",
Contract.TABLE_NAME,
Contract.Columns.TASK,
task);
helper = new DBHelper(getActivity());
SQLiteDatabase sqlDB = helper.getWritableDatabase();
sqlDB.execSQL(sql);
update();
}

Categories