Adding elements into view list via edit text field - java

I am trying to make a edit text field where i enter a string and then by pressing the button beside it this string is added into a list view on a fragment.
When i compile the code i get the following error:
10-19 15:04:14.620 21147-21147/com.example.gasper.test E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.gasper.test.TopRatedFragment.onCreateView(TopRatedFragment.java:57)
this is the line 57
b.setOnClickListener(listener);
Does anybody now what is wrong here? I am a beginer in android development so dont judge me :)
I also tried somethong like this but still not working:
if(listener !=null){
b.setOnClickListener(listener);}
package com.example.gasper.test;
Here is the full code:
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.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import static com.example.gasper.test.R.layout.fragment_top_rated;
public class TopRatedFragment extends Fragment {
String[] myString =new String[] {"0ne","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve"};
List list = new ArrayList<String>();
ArrayAdapter<String> adapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(fragment_top_rated, container, false);
for(String activity : myString){
list.add(activity);
}
adapter = new ArrayAdapter<String>(this.getActivity(), fragment_top_rated,R.id.textView,list);
ListView listView = (ListView) rootView.findViewById(R.id.listView);
Button b = (Button) getActivity().findViewById(R.id.button);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText edit = (EditText) getActivity().findViewById(R.id.editText);
list.add(edit.getText().toString());
edit.setText("");
adapter.notifyDataSetChanged();
}
};
getActivity().setContentView(R.layout.fragment_top_rated);
b.setOnClickListener(listener);
listView.setAdapter(adapter);
return rootView;
}
}
Here is the fragment_top:rated.xml file:
<?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:orientation="vertical"
android:background="#ffefe4fa" >
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="false"
android:layout_alignParentRight="false"
android:layout_below="#+id/editText" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editText1"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="#string/edit_message"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
android:id="#+id/button1"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:onClick=""/>
</RelativeLayout>

replace this line of your code
Button b = (Button) getActivity().findViewById(R.id.button);
with this line and give it a try
Button b = (Button) rootView.findViewById(R.id.button1);
Edit 1:
adapter = new ArrayAdapter<String>(this.getActivity(), fragment_top_rated,R.id.textView,list);
this line of code shows you are using same xml...is there any textView defined in your this xml..just create a new xml for your list view..and use it here..

It seems that you mistyped the id:
Button b = (Button) getActivity().findViewById(R.id.button);
Your layout has button1 not button.
Edit:
Also the button is found in your fragment's layout not your activity's, so look for it there like this:
Button b = (Button) rootView.findViewById(R.id.button1);

ArrayAdapter has a an internal List of its own. The strings list you pass to its constructor is merely copied to the internal list to initialize the adapter.
User adapter object's add() or addAll() to actually add items to ArrayAdapter.
Change
list.add(edit.getText().toString());
to
adapter.add(edit.getText().toString());
Update 1:
Button b = (Button) getActivity().findViewById(R.id.button);
You are using a fragment and its not yet attached to activity, so activity can't find anything from a view that's not attached to it:
Button b = (Button) rootView.findViewById(R.id.button);

Related

How use OnClickListener in Fragments

This is my code. I'm still learning android studio. I want to show a toast when the button is clicked but when I run the application and click the button it does nothing. (this is a Fragment). Does anyone know how to fix this? I tried putting "onClick" method in the xml(android:onClick="onClick") then the app crashed as soon as I clicked the button.
fragment_fragment_course.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".fragmentCourse">
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Course"
android:textSize="25sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/btnCourse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/textView2"
app:layout_constraintStart_toStartOf="#+id/textView2"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
fragmentCourse.java
package com.example.sma;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
public class fragmentCourse extends Fragment implements View.OnClickListener {
Button btn2;
public fragmentCourse() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View CView = inflater.inflate(R.layout.fragment_fragment_course, container, false);
btn2 = (Button)CView.findViewById(R.id.btnCourse);
final TextView txt = (TextView)CView.findViewById(R.id.textView2);
btn2.setOnClickListener(this);
return CView;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnCourse:
Toast.makeText(getActivity(), "done", Toast.LENGTH_SHORT).show();
break;
}
}
}
Override onViewCreated method and move below code to there. You can't access the views in onCreateView of fragment.
btn2 = (Button)CView.findViewById(R.id.btnCourse);
final TextView txt = (TextView)CView.findViewById(R.id.textView2);
btn2.setOnClickListener(this)

findviewByid returns null for listview

Main activity
List View returns a null value
package com.example.dell.ab;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import java.lang.reflect.Array;
public class MainActivity extends AppCompatActivity {
TextView textView;
Button a, b, c, d;
String deleteelement;
ListView listView;
String dataarray;
Myadapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
listView=findViewById(R.id.listview);
}
public void sh(View view)
{
Log.d("am"," "+textView);
Log.d("am"," "+listView);
dataarray=textView.getText().toString();
adapter= new Myadapter(this,dataarray);
listView.setAdapter(adapter);
}
}
List activity. x ml
<TextView
android:id="#+id/texttobedisplayed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:text="score" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listview"
android:layout_marginTop="50dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
The problem here is ListView gives a null value
whereas text view which is a part of activity.xml whose code I did not put return a proper value
CHANGE INFLATED XML and TEXTVIEW ID
setContentView(R.layout.activity_list);
textView = (TextView)findViewById(R.id.texttobedisplayed);
listView= (ListView)findViewById(R.id.listview);
it seems that your xml file name is differ from activity_main that you pass to setContentView. change the parameter you pass to this method to real file name.
Your declaration is wrong listview and text
textView = (TextView)findViewById(R.id.texttobedisplayed );
listView= (ListView)findViewById(R.id.listview);

How to add row to listView on button click in android studio?

I am using a custom adapter for my ListView which I already don't understand as much as I would like to. I can find information online on how to add a row to ListView but it doesn't integrate nicely into my code, I'm guessing because I'm using a custom adapter. I have my setOnClickListener() method for my button in my Main Activity and have been experimenting there but just cant figure it out I'm also not sure if my method is in the right place?
this is the mainActivity
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import static java.util.logging.Logger.global;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final String[] Chores = {""};
ListAdapter MyAdapter = new CustomAdapter(this, Chores);
ListView listViewObject = (ListView)findViewById(R.id.customListView_ID);
listViewObject.setAdapter(MyAdapter);
listViewObject.setOnItemClickListener(
new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
String ChoreString = String.valueOf(parent.getItemAtPosition(position));
}
}
);
// this is where I am trying to have button click add another row to my listView
final Button button = (Button) findViewById(R.id.button_ID);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//this is where I am stuck
}
});
}
}
here is my CustomAdapter class
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
class CustomAdapter extends ArrayAdapter{
public CustomAdapter(Context context, String[] choreText) {
super(context, R.layout.custon_listview_row, choreText);
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater myInflater = LayoutInflater.from(getContext());
View customView = myInflater.inflate(R.layout.custon_listview_row, parent, false);
String singleListItem = (String) getItem(position);
EditText choreText = (EditText) customView.findViewById(R.id.editText_ID);
ImageButton imageButton = (ImageButton) customView.findViewById(R.id.imageButton_ID);
choreText.setText(singleListItem, TextView.BufferType.EDITABLE);
imageButton.setImageResource(R.drawable.clock);
return customView;
}
}
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:id="#+id/activity_main"
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.example.emilythacker.chorelist.MainActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/customListView_ID"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginTop="50dp" />
<Button
android:text="Add Chore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/button_ID" />
</RelativeLayout>
and custom_listview_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="60dp">
<ImageButton
android:layout_width="60dp"
android:scaleType="fitCenter"
app:srcCompat="#drawable/clock"
android:id="#+id/imageButton_ID"
android:layout_height="60dp"
android:background="#null"
android:layout_alignParentRight="true"
android:padding="5dp"
android:layout_weight="1" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:id="#+id/editText_ID"
android:layout_alignParentLeft="true"
android:alpha = ".5"
android:hint="Enter chore"
android:maxLines="1"
android:inputType="text"
/>
</RelativeLayout>
First make your list into an ArrayList instead of String array.
private ArrayList<String> arrayList;
In the buttons onClick
arrayList.add("New Item");
((ArrayAdapter)MyAdapter).notifyDataSetChanged();
public void onClick(View v) {
String stringToAdd = ... //
MyAdapter.add(stringToAdd);
}
You will need to add final to the adapter declaration for this to work:
final ListAdapter MyAdapter = new CustomAdapter(this, Chores);
EDIT
To add more than one row at a time:
public void onClick(View v) {
String[] rowsToAdd = ... //
MyAdapter.addAll(rowsToAdd);
}

ListView only one list entry play button works

I'm trying to make a ListView activity following the example from this website
http://cyrilmottier.com/2011/11/23/listview-tips-tricks-4-add-several-clickable-areas/
in which I'm using data from my database and using a BaseAdapter everything seems to work fine (the onListItemClick,the textview loading my data) but my "play" button on the right of the list items will not work.I am using a framelayout in my list-items xml if that helps.
---UPDATE---
None of those answers solved my question but after fiddling around I got the first entry play button working but the other entry play buttons do not work only the first one works.
Here is the new codes for my list activity and xml.
PlayAFriend Activity
package com.fullfrontalgames.numberfighter;
import com.fullfrontalgames.numberfighter.DBAdapter;
import com.fullfrontalgames.numberfighter.R;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class PlayAFriend extends ListActivity{
DBAdapter DBAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.list_items);
final DBAdapter db = new DBAdapter(this);
DBAdapter = db.open();
ListView FriendLV = (ListView) findViewById(android.R.id.list);
Button playbutton = (Button) findViewById(R.id.playbutton);
FriendLV.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "test", Toast.LENGTH_SHORT).show();
}
});
playbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("com.fullfrontalgames.numberfighter.Fightattacker"));
}
});
Cursor friendslist = db.GetAllFriends();
String[] from = new String[] {"FRIENDS"}; // your column/columns here
int[] to = new int[] {R.id.textview_friends};
#SuppressWarnings("deprecation")
ListAdapter cursorAdapter = new SimpleCursorAdapter(this, R.layout.list_items, friendslist, from, to,0);
FriendLV.setAdapter(cursorAdapter);
}
}
list_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"
android:descendantFocusability="blocksDescendants"
android:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</ListView>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:background="#drawable/searchimageview"
android:orientation="vertical" >
<TextView
android:id="#+id/textview_friends"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/black"
android:textStyle="bold"
android:textSize="40dp"
android:layout_gravity="center" />
<Button
android:id="#+id/playbutton"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_gravity="right"
android:background="#drawable/playbutton" />
</FrameLayout>
</LinearLayout>
May be you are in wrong way.You have to try this link insted of textView you have to used button.
http://wowjava.wordpress.com/2011/03/26/dynamic-listview-in-android/
If you have any problem then let me know.
Try the below
In getView()
Button b=(Button) convertView.findViewById(R.id.playbutton);
b.setOnClickListener(new OnClickListener()
{
if (position != ListView.INVALID_POSITION) {
startActivity(newIntent("com.fullfrontalgames.numberfighter.Fightattacker"));
}
});
Also you should be using a ViewHolder for smooth scrolling and performance. Details of which are available in the link below.
http://developer.android.com/training/improving-layouts/smooth-scrolling.html
Update
Sorry for the late update but I sovled this issue on my own by adding a android:onClick attribute to my play button and then defining the public onButtonClick method in my class.
<Button
android:id="#+id/playbutton"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_gravity="right"
android:onClick="OnButtonClick"
android:background="#drawable/playbutton" />
Class
public void OnButtonClick(View view) {
startActivity(new Intent(
"com.fullfrontalgames.numberfighter.Fightattacker"));
}

Reading and Displaying form data on Android

I've a simple form page that I want to use to fetch user data. It contains three fields.
1.Name Field (Edit Text type)
2.Radio Button "Male or Female" (Radio Group within Radio Button)
3.Drop Down Menu "choose your country" (Spinner)
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="1px">
<TextView
android:id="#+id/tasks_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/tasks"/>
<ListView
android:id="#id/android:list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/tasks_title"
android:layout_above="#+id/add_button"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#id/android:empty"
android:text="#string/no_tasks"
android:gravity="center_vertical|center_horizontal"
android:layout_below="#id/tasks_title"
android:layout_above="#+id/add_button"/>
<Button
android:id="#id/add_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/add_task"
android:layout_alignParentBottom="true"
/>
</RelativeLayout>
I've created another Activity called it FormActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Spinner;
public class FormActivity extends Activity {
private Button submitbutton;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
submitbutton=(Button)findViewById(R.id.submit_button);
submitbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(FormActivity.this, DisplayActivity.class);
startActivity(intent);
}
});
/**Implements DropDownMenu (spinner) by pushing items into an array an displaying them**/
Spinner spinner = (Spinner)findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.countries_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
}
}
How can I use the data from the xml file to be displayed on another page. Please give me instructions as I am learning android now.
Thanks and have a good day
Intent intent = new Intent(FormActivity.this, DisplayActivity.class);
EditText inputName = (EditText) findViewById(R.id.inputText);
String name = inputName.getText().toString();
intent.putExtra("name" , name );
startActivity(intent);
In the new Intent you use this snip:
Bundle extras = getIntent().getExtras();
String name = extras.getString("name");
You can pass data as Extras in the intent but you can also have a custom class, inherited from Application, make it visible and fill it with values that you need. This is useful when you have a constant domain across your application (the same user, the initialization values, etc.) or 'global' functions (read-write local data, test any resource, etc.).
You add the application:name to the Manifest and then you can add your custom code in your own application class.

Categories

Resources