Null Pointer Exception when invoking setOnItemClickListener - java

New to Android and Java and learning by doing but I seem to be missing something fundamental on detecting item clicks in a ListView.
I have an activity that is a couple of buttons with a ListView below them. Each ListView item has an icon that can be clicked on, that will eventually go to another activity, and a timestamp (currently just indicating the click worked via Toast). Click detection on the icon is working but I am trying to implement selection of items in the ListView and that is where I am running into trouble.
I have reviewed numerous examples such as this and I think I am doing it as prescribed but I am obviously missing something, as I am receiving a runtime exception "java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)' on a null object reference:"
Here is the layout for the view:
<?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="com.example.foo.magma.ViewPassagesActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/linearLayout">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Update"
android:onClick="update"
android:id="#+id/updateButton"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_weight="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete"
android:onClick="delete"
android:id="#+id/deleteButton"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_weight="1"/>
</LinearLayout>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/passagesListView"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_below="#+id/linearLayout" />
</RelativeLayout>
Here is the layout for an item in the ListView. As mentioned, it an icon on the left with a timestamp:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/icon"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="10dp"
android:layout_marginTop="4dp"
android:src="#drawable/curve" >
</ImageView>
<TextView
android:id="#+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Timestamp: "
android:textStyle="bold"
android:textSize="20dp"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/icon"
android:layout_toEndOf="#+id/icon">
android:layout_toRightOf="#+id/icon"
</TextView>
<TextView
android:id="#+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="layouttesttime"
android:textSize="20dp"
android:layout_below="#+id/date"
android:layout_alignRight="#+id/date"
android:layout_alignEnd="#+id/date"
android:layout_alignLeft="#+id/date"
android:layout_alignStart="#+id/date">
</TextView>
<TextView
android:id="#+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="layouttestdate"
android:textSize="20dp"
android:layout_alignTop="#+id/icon"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_toRightOf="#+id/label"
android:layout_toEndOf="#+id/label">
</TextView>
</RelativeLayout>
Here is he onCreate() from my activity, which sets my adapter:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_passages);
ListView passagesListView = (ListView) findViewById(R.id.passagesListView);
assert passagesListView != null;
buildPassageList();
PassagesViewAdapter adapter = new PassagesViewAdapter(this, R.layout.passages_row_layout, passages);
passagesListView.setAdapter(adapter);
}
And here is where I am having the issue. The OnClickListener for the icon works. My intent is to detect selection of a ListView item so that it can be deleted. However, when I add the invocation of setOnItemClickListener(), I receive a runtime exception.
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class PassagesViewAdapter extends ArrayAdapter<Passage>{
private int resource;
private List<Passage> passages;
public PassagesViewAdapter(Context context, int resource, List<Passage> passages) {
super(context, resource, passages);
this.resource = resource;
this.passages = passages;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater li = LayoutInflater.from(getContext());
view = li.inflate(resource, null);
}
Passage passage = this.passages.get(position);
TextView time = (TextView) view.findViewById(R.id.time);
TextView date = (TextView) view.findViewById(R.id.date);
ImageView icon = (ImageView) view.findViewById(R.id.icon);
icon.setTag(new Integer(position));
final String positionStr = icon.getTag().toString();
// This works great!
icon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "You clicked on " + positionStr, Toast.LENGTH_SHORT).show();
}
});
ListView passagesListView = (ListView) view.findViewById(R.id.passagesListView);
assert passagesListView != null;
// ** This call results in a runtime error for null pointer reference.
passagesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position,long arg3) {
Toast.makeText(getContext(), "Foo", Toast.LENGTH_SHORT).show();
}
});
time.setText(passage.getPassageTime());
date.setText(passage.getPassageDate());
return view;
}
}

That because the View you have in your adapter represents the View you see in the list, not the layout of your ViewPassagesActivity. You do not have a ListView in your ListView items so it cannot be found and findViewById returns null. If you move the part where you set the OnItemClickListener to the onCreate of your ViewPassagesActivity, everything should be working fine
Remove this part from your adapter
// ** This call results in a runtime error for null pointer reference.
passagesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position,long arg3) {
Toast.makeText(getContext(), "Foo", Toast.LENGTH_SHORT).show();
}
});
and add it to your Activity's onCreate like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_passages);
ListView passagesListView = (ListView) findViewById(R.id.passagesListView);
assert passagesListView != null;
buildPassageList();
PassagesViewAdapter adapter = new PassagesViewAdapter(this, R.layout.passages_row_layout, passages);
passagesListView.setAdapter(adapter);
// ** This call results in a runtime error for null pointer reference.
passagesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position,long arg3) {
Toast.makeText(getContext(), "Foo", Toast.LENGTH_SHORT).show();
}
});
}

Try extending your Adapter from BaseAdapter.
This
public class PassagesViewAdapter extends ArrayAdapter<Passage>{
to this
public class PassagesViewAdapter extends BaseAdapter {
Also your setOnItemClickListener needs to be in the onCreate function in your activity, not in the adapter.

Related

how can i code public class for SimpleCursorAdapter?

I am new to android and I need to use ListView for my project. I use a sample from the internet which has no public class for ListView so I am not able to code flexible. how can I code public class for this.
public class LIGHTS extends AppCompatActivity {
ListView users_list;
private DatabaseManager dbManager;
private SimpleCursorAdapter adapter;
private DatabaseHelper dbHelper;
final String[] from = new String[]{dbHelper._ID, dbHelper.TITLE, dbHelper.DESC};
final int[] to = new int[]{R.id.id, R.id.KEYCODE, R.id.NAME};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lights);
startconnection();
dbManager = new DatabaseManager(this);
dbManager.open();
Cursor cursor = dbManager.fetch();
users_list = findViewById(R.id.users_list);
adapter = new SimpleCursorAdapter(this, R.layout.adapter, cursor, from, to, 0);
users_list.setAdapter(adapter);}
and the fetch() is in below code in dbmanager:
public Cursor fetch() {
String[] columns = new String[]{dbHelper._ID, dbHelper.TITLE, dbHelper.DESC};
Cursor cursor = database.query(dbHelper.TABLE_NAME, columns, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
Here's an example based upon your code that handles clicking a button for each item in the list.
If you click a switch then it displays the id of the item via a toast.
This utilises a Custom Adapter based upon (extends) the CursorAdapter class.
First the layout adapter.xml used for the item (should have the basics of your's and includes a switch who's id is the_switch) :-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/id"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/KEYCODE"
android:layout_width="0dp"
android:layout_weight="2"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/NAME"
android:layout_width="0dp"
android:layout_weight="6"
android:layout_height="wrap_content" />
<Switch
android:id="#+id/the_switch"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:focusable="false"
/>
</LinearLayout>
The Activity Lights.java is now :-
public class Lights extends AppCompatActivity {
ListView users_list, alt_users_list;
private DatabaseManager dbManager;
private MyCustomCursorAdapter adapter;
//private DatabaseManager dbHelper; //?????? a second not needed
Cursor cursor;
Context mContext;
//<<<<<<<<<< Not needed although could be passed
//final String[] from = new String[]{DatabaseManager._ID, DatabaseManager.TITLE, DatabaseManager.DESC};
//final int[] to = new int[]{R.id.id, R.id.KEYCODE, R.id.NAME};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
setContentView(R.layout.activity_lights);
startconnection(); //?????? dummied out
users_list = findViewById(R.id.users_list);
alt_users_list = findViewById(R.id.alt_users_list);
dbManager = new DatabaseManager(this);
dbManager.open();
manageListView(); //Handles the ListView
}
// Moved here handles list refresh if called (e.g. in onResume)
private void manageListView() {
cursor = dbManager.fetch();
//Setup the adapter if not already setup else swaps (refreshes) the cursor
if (adapter == null) {
adapter = new MyCustomCursorAdapter(this, cursor);
users_list.setAdapter(adapter);
users_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(mContext,"You clicked on the item with an ID of " + String.valueOf(id),Toast.LENGTH_SHORT).show();
}
});
} else {
adapter.swapCursor(cursor);
}
}
private void startconnection(){}
#Override
protected void onDestroy() {
super.onDestroy();
// Close the Cursors when done with them
cursor.close();
}
#Override
protected void onResume() {
super.onResume();
// Refresh the listviews when returning to the activity
manageListView();
}
}
Comments try to explain changes (basically it is quite similar).
The biggest change is that the setting up of the listview has been moved to a method of it's own, which also handles refreshing the listview (redisplaying it after the underlying data has been changed).
The instantiation of the adapter is also simpler than for the SimpleCursorAdapter (the layout and column to view handling coded in the adapter).
The adapter myCustomAdapter.java is :-
public class MyCustomCursorAdapter extends CursorAdapter {
public MyCustomCursorAdapter(Context context, Cursor c) {
super(context, c, 0);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
if (position % 2 == 0) {
view.setBackgroundColor(0xFFAAAAFF);
} else {
view.setBackgroundColor(0xAAAAAAFF);
}
return view;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.adapter,parent,false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
((TextView)view.findViewById(R.id.id)).setText(cursor.getString(cursor.getColumnIndex(DatabaseManager._ID)));
((TextView)view.findViewById(R.id.KEYCODE)).setText(cursor.getString(cursor.getColumnIndex(DatabaseManager.TITLE)));
((TextView)view.findViewById(R.id.NAME)).setText(cursor.getString(cursor.getColumnIndex(DatabaseManager.DESC)));
Switch thisswitch = view.findViewById(R.id.the_switch);
thisswitch.setTag(cursor.getString(cursor.getColumnIndex(DatabaseManager._ID)));
thisswitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Toast.makeText(buttonView.getContext(),
"You clicked the switch for ID " + (String) buttonView.getTag() +
" the status is now " + (new Boolean(isChecked)).toString(),
Toast.LENGTH_SHORT)
.show()
;
}
});
}
}
bindView has primarily been used it :-
binds the values from the columns of the cursor to the views for each item
and in this case sets the tag of the switch to the id and then adds an onCheckChangedListener for the Button.
bindView has the advantage that the cursor and context are passed to it.
getView can also be used, it has the advantage of having the position of the item in the list passed.
In this case it has been used to alternate the background colour for each item.
Result
Here's a screen shot showing the toast (note testing data was added to the underlying database, so this will obviously vary from yours) :-
Additional
It might be that you need to handle the switch check change in the owning activity.
The following changes show a basic means, via an interface, of handling the switch event in the activity, rather than in the adapter.
First the interface myOnCheckedChangedInterface.java
public interface myOnCheckedChangedInterface {
void myOnCheckedChangedHandler(String id, boolean check_status);
}
Second change Lights.java by adding the handler method myOnCheckedChangedHandler
#Override
public void myOnCheckedChangedHandler(String id, boolean check_status) {
Toast.makeText(
this,
"You changed the status for the row with an id of " + id +
" the status is now " + new Boolean(check_status).toString(),
Toast.LENGTH_SHORT).show();
}
Ignore the error that the method doesn't override method from it's superclass.
Third change the Class declaration to implement the interface by adding implements myOnCheckedChangedInterface as per :-
public class Lights extends AppCompatActivity implements myOnCheckedChangedInterface {
Lastly change MyCustomCursorAdapter to be able to call the myOnCheckedChangedHandler
e.g.
public class MyCustomCursorAdapter extends CursorAdapter {
Lights calling_activity; //<<<<<<<<<<########### ADDED for interface
public MyCustomCursorAdapter(Context context, Cursor c) {
super(context, c, 0);
this.calling_activity = (Lights) context; //<<<<<<<<<<########### ADDED for interface
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
if (position % 2 == 0) {
view.setBackgroundColor(0xFFAAAAFF);
} else {
view.setBackgroundColor(0xAAAAAAFF);
}
return view;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.adapter,parent,false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
((TextView)view.findViewById(R.id.id)).setText(cursor.getString(cursor.getColumnIndex(DatabaseManager._ID)));
((TextView)view.findViewById(R.id.KEYCODE)).setText(cursor.getString(cursor.getColumnIndex(DatabaseManager.TITLE)));
((TextView)view.findViewById(R.id.NAME)).setText(cursor.getString(cursor.getColumnIndex(DatabaseManager.DESC)));
Switch thisswitch = view.findViewById(R.id.the_switch);
thisswitch.setTag(cursor.getString(cursor.getColumnIndex(DatabaseManager._ID)));
thisswitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
/**
Toast.makeText(buttonView.getContext(),
"You clicked the switch for ID " + (String) buttonView.getTag() +
" the status is now " + (new Boolean(isChecked)).toString(),
Toast.LENGTH_SHORT)
.show()
**/
calling_activity.myOnCheckedChangedHandler((String)buttonView.getTag(),isChecked); //<<<<<<<<<<########### ADDED for interface
}
});
}
}
See commments with //<<<<<<<<<<########### ADDED for interface for changes
The original Toast has been commented out as it is no longer needed
Note this isn't the tidiest way as the Adapter is tied to a Lights activity, it's just meant to be a simple example.
In order to customize a ListAdapter, you need to create your own custom ListAdapter class that is based on, or 'extends' the built-in ListAdapter (such as SimpleListAdapter or BaseAdapter). Then, you can customize the appearance and what fields of data to display. Below is an example of a custom ListAdapter I called ClaimsListAdapter.java that 'extends' the built-in class called BaseAdapter:
package com.mycompany.myapp.adapter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import com.mycompany.myapp.ClaimListFragment;
import com.mycompany.myapp.R;
import com.mycompany.myapp.TripListFragment;
import com.mycompany.myapp.model.ClaimItem;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
// You might be able to extend SimpleListAdapter instead if you wish
public class ClaimListAdapter extends BaseAdapter {
private Context context;
private ArrayList<ClaimItem> claimItems;
ClaimListFragment fragment;
//I'm passing references to both the active Context as well as the active Fragment
//You might only need to pass the active Context
public ClaimListAdapter(ClaimListFragment fragment, Context context, ArrayList<ClaimItem> claimItems){
this.context = context;
this.claimItems = claimItems;
this.fragment = fragment;
}
#Override
public int getCount() {
return claimItems.size();
}
#Override
public Object getItem(int position) {
return claimItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint("InflateParams")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
//This is the layout for the list item. A SimpleListAdapter doesn't need one
//since it only has one text view, but this allows you to create multiple lines
//and/or multiple fields, buttons, checkboxes etc if you wish
convertView = mInflater.inflate(R.layout.claim_list_item, null);
}
//Get a reference to all of the items in the layout you wish to change
Button btnDelete = (Button) convertView.findViewById(R.id.claim_delete_in_list);
//Note, here I'm saving the row number in the tag of the button to tell the fragment
//which row in the array to delete.
btnDelete.setTag(position);
//Here is an example of setting a click listener for a button in the list
btnDelete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Integer position = (Integer)v.getTag();
//Call the Public method in the parent Fragment (or Activity) to delete from the
//array and refresh the list
fragment.deleteItemList(position);
}
});
btnDelete.setVisibility(View.GONE);
//Get a reference to all of the text fields in the list item
TextView txtTitle = (TextView) convertView.findViewById(R.id.claim_title);
TextView txtStatus = (TextView) convertView.findViewById(R.id.claim_status);
TextView txtDate = (TextView) convertView.findViewById(R.id.claim_date);
TextView txtDistance = (TextView) convertView.findViewById(R.id.claim_distance);
TextView txtAmount = (TextView) convertView.findViewById(R.id.claim_amount);
String claim_title = claimItems.get(position).getDocumentID();
String claim_status = claimItems.get(position).getClaimStatus();
txtTitle.setText(claim_title);
txtStatus.setText(claim_status);
return convertView;
}
}
And the claim_list_item.xml layout file:
<?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:baselineAligned="false"
android:orientation="horizontal">
<LinearLayout
android:id="#+id/whole_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.7"
android:background="#drawable/list_selector_light"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/top_layout"
android:layout_width="match_parent"
android:layout_height="20dp"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
android:layout_weight="0.48"
android:background="#00000000"
android:orientation="horizontal" >
<TextView
android:id="#+id/claim_title"
android:layout_width="match_parent"
android:layout_height="20dp"
android:layout_marginBottom="2dp"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:layout_marginRight="5dp"
android:layout_marginEnd="5dp"
android:layout_weight="0.73"
android:background="#00000000"
android:gravity="start|center_vertical"
android:text=""
android:textColor="#FFFFFFFF"
android:textSize="16sp" />
<TextView
android:id="#+id/claim_status"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginBottom="2dp"
android:layout_marginEnd="5dp"
android:layout_marginRight="5dp"
android:background="#00000000"
android:gravity="end|center_vertical"
android:text=""
android:textColor="#FFFFFFFF"
android:textSize="14sp" />
</LinearLayout>
<LinearLayout
android:id="#+id/bottom_layout"
android:layout_width="match_parent"
android:layout_height="20dp"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
android:layout_weight="0.48"
android:background="#00000000"
android:orientation="horizontal" >
<TextView
android:id="#+id/claim_date"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:background="#00000000"
android:gravity="start|center_vertical"
android:text=""
android:textColor="#FFFFFFFF"
android:textSize="14sp" />
<TextView
android:id="#+id/claim_distance"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="50dp"
android:layout_marginStart="50dp"
android:layout_marginRight="50dp"
android:layout_marginEnd="50dp"
android:layout_weight="1.0"
android:layout_gravity="center"
android:background="#00000000"
android:gravity="center|center_vertical"
android:text=""
android:textSize="12sp"
android:textColor="#FFFFFFFF"/>
<TextView
android:id="#+id/claim_amount"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginBottom="2dp"
android:layout_marginEnd="5dp"
android:layout_marginRight="5dp"
android:background="#00000000"
android:gravity="end|center_vertical"
android:text=""
android:textColor="#FFFFFFFF"
android:textSize="12sp" />
</LinearLayout>
</LinearLayout>
<Button
android:id="#+id/claim_delete_in_list"
android:layout_width="100dp"
android:layout_height="match_parent"
android:layout_weight="0.3"
android:text="#string/delete"
android:textSize="16sp"
android:textColor="#FFFFFFFF"
android:background="#android:color/holo_red_dark"
/>
</LinearLayout>

How to add listView with scroll inside a Popup window in android studio?

I am trying to make an android app which opens a popup window when clicked on a button. And, the popup window has four TextView with heading and 4 listView with options. However, I could not add listView inside a popup window. The popup window opens when clicking a button but when I add listView and its adapter and try to run it, the app crashes. I want the layout of PopUp window to be as one in news.xml file.
activity_main.xml
<ScrollView 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:fillViewport="true"
android:visibility="visible"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/linear">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/news1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_marginStart="15dp"
android:text="#string/news" />
</RelativeLayout>
</LinearLayout>
</ScrollView>
MainActivity.java
package com.example.abina.popup;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import static android.view.Gravity.NO_GRAVITY;
public class MainActivity extends AppCompatActivity {
private Button news1;
private PopupWindow popupWindow;
private LayoutInflater layoutInflater;
private LinearLayout linearLayout;
ListView lst;
String [] local = {"asdf","Sgadf","adfhtr","trdbfa"};
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//for listView 1
lst = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,local);
lst.setAdapter(adapter);
lst.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(MainActivity.this,local[i],Toast.LENGTH_SHORT).show();
}
});
linearLayout = (LinearLayout) findViewById(R.id.linear);
news1 = (Button) findViewById(R.id.news1);
news1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
layoutInflater = (LayoutInflater) getApplication().getSystemService(LAYOUT_INFLATER_SERVICE);
ViewGroup container = (ViewGroup) layoutInflater.inflate(R.layout.news,null);
popupWindow = new PopupWindow(container,800,1300,true);
popupWindow.showAsDropDown(news1);
container.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
popupWindow.dismiss();
return false;
}
});
}
});
}
}
news.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"
android:background="#ABEBC6">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true">
<ListView
android:id="#+id/listView1"
android:layout_width="160dp"
android:layout_height="184dp"
android:layout_alignParentStart="true"
android:layout_below="#+id/textView"
android:layout_marginStart="13dp" />
<TextView
android:id="#+id/textView"
android:layout_width="109dp"
android:layout_height="33dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="30dp"
android:layout_marginTop="20dp"
android:text="#string/local" />
<TextView
android:id="#+id/textView2"
android:layout_width="108dp"
android:layout_height="33dp"
android:layout_alignParentEnd="true"
android:layout_alignTop="#+id/textView"
android:layout_marginEnd="30dp"
android:text="#string/national" />
<ListView
android:id="#+id/listView2"
android:layout_width="160dp"
android:layout_height="184dp"
android:layout_alignParentEnd="true"
android:layout_alignTop="#+id/listView1" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="260dp">
<TextView
android:id="#+id/textView3"
android:layout_width="109dp"
android:layout_height="33dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="30dp"
android:layout_marginTop="20dp"
android:text="#string/sports1" />
<TextView
android:id="#+id/textView4"
android:layout_width="108dp"
android:layout_height="33dp"
android:layout_alignParentEnd="true"
android:layout_alignTop="#+id/textView3"
android:layout_marginEnd="43dp"
android:text="#string/sports2" />
<ListView
android:id="#+id/listView3"
android:layout_width="160dp"
android:layout_height="184dp"
android:layout_alignParentStart="true"
android:layout_below="#+id/textView3"
android:layout_marginStart="20dp" />
<ListView
android:id="#+id/listView4"
android:layout_width="162dp"
android:layout_height="184dp"
android:layout_alignParentEnd="true"
android:layout_below="#+id/textView4" />
</RelativeLayout>
</RelativeLayout>
strings.xml
<resources>
<string name="app_name">Popup</string>
<string name="news">Check Latest News!</string>
<string name="local">Local News</string>
<string name="national">National News</string>
<string name="sports1">Sports One</string>
<string name="sports2">Sports Two</string>
<string-array name="local">
<item>Star Ledger</item>
<item>Ny Times</item>
<item>The Record</item>
<item>Trentorian</item>
</string-array>
</resources>
The problem is that your list doesn't exist in your activity_main layout. Rather it exists in popup window.
change your onCreate() method as the code below and it should work fine.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//for listView 1
linearLayout = (LinearLayout) findViewById(R.id.linear);
news1 = (Button) findViewById(R.id.news1);
news1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
layoutInflater = (LayoutInflater) getApplication().getSystemService(LAYOUT_INFLATER_SERVICE);
ViewGroup container = (ViewGroup) layoutInflater.inflate(R.layout.news,null);
popupWindow = new PopupWindow(container,800,1300,true);
lst = container.findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,local);
lst.setAdapter(adapter);
lst.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(MainActivity.this,local[i],Toast.LENGTH_SHORT).show();
}
});
popupWindow.showAsDropDown(news1);
container.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
popupWindow.dismiss();
return false;
}
});
}
});
}
Hope this helps you.
Best regards,
In your action listener add this one:
news1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
PopupWindow popupWindow = new PopupWindow(getApplicationContext());
ArrayList<String> sortList = new ArrayList<>();
sortList.add("A to Z");
sortList.add("Z to A");
sortList.add("Any");
sortList.add("Test");
ArrayAdapter<String> adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_dropdown_item_1line,
sortList);
ListView listViewSort = new ListView(getApplicationContext());
listViewSort.setAdapter(adapter);
// set on item selected
listViewSort.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(),
"You select in popup menu" + adapterView.getAdapter().getItem(i).toString(), Toast.LENGTH_LONG).show();
popupWindow.dismiss();
}
});
popupWindow.setFocusable(true);
popupWindow.setWidth(WindowManager.LayoutParams.FILL_PARENT);
popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
popupWindow.setContentView(listViewSort);
popupWindow.showAsDropDown(view, 0, 0);
});
}
Here example popup menu with two listviews and textviews:
PopupWindow popupWindow = new PopupWindow(getApplicationContext());
LayoutInflater inflater = (LayoutInflater) getApplicationContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.popup_element,
(ViewGroup) view, false);
//List first
TextView nameOfList1 = layout.findViewById(R.id.text1);
nameOfList1.setText("List one:");
ListView mListView1 = layout.findViewById(R.id.listView1);
final String[] data1 = {"Value from list 1", "Value from list 2", "Value from list 3", "Value from list 4",
"Value from list 5", "Value from list 6"};
mListView1.setAdapter(new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, data1));
mListView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(), "You select value from list one " + data1[i], Toast.LENGTH_LONG).show();
}
});
//List second
TextView nameOfList2 = layout.findViewById(R.id.text2);
nameOfList2.setText("Select planet from list");
ListView mListView2 = layout.findViewById(R.id.listView2);
final String[] data2 = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"};
mListView2.setAdapter(new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, data2));
mListView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(), "You select plane " + data2[i], Toast.LENGTH_LONG).show();
}
});
popupWindow.setFocusable(true);
popupWindow.setWidth(WindowManager.LayoutParams.FILL_PARENT);
popupWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
popupWindow.setContentView(layout);
popupWindow.showAsDropDown(view, 0, 0);
And popup_element.xml:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scrollojt"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:id="#+id/text1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/listView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#f00"></ListView>
<TextView
android:id="#+id/text2"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<ListView
android:id="#+id/listView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/listView1"
android:background="#0f0"></ListView>
</LinearLayout>
</ScrollView>

Same Fragment Should Appear one below another according to the Number Selected in Spinner. HOW?

I have a Small Fragment with three EditText and i have a Spinner with 1,2,3 as options in It.
What i want to do is that, when i select '1' from the Spinner, i want my fragment to appear below the spinner in same Activity.
And when i select '2' in Spinner, the same Fragment Should Appear Twice one below another in the same Activity and similarly for when i select '3' from Spinner.
HERE IS THE JAVA CODE
package com.globaltech2u.databaseapp1;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Spinner spinner;
private String bookno[] = {"#","1","2","3","4"};
private ArrayAdapter<String> arrayAdapter;
private EditText editText,editText2,editText3;
private CheckBox checkBox;
private Button button;
private SQLiteDatabase db;
private Database mySQLiteOpenHelper;
private Fragment fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText)findViewById(R.id.et1);
editText2 = (EditText)findViewById(R.id.et2);
editText3 = (EditText)findViewById(R.id.et3);
checkBox = (CheckBox)findViewById(R.id.cb1);
button = (Button)findViewById(R.id.button);
spinner = (Spinner)findViewById(R.id.booknoselectspinner);
arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, bookno);
spinner.setAdapter(arrayAdapter);
mySQLiteOpenHelper = new Database(this, "bookrecord", null, 1);
db = mySQLiteOpenHelper.getWritableDatabase();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String bookname = editText.getText().toString();
String bookno = editText2.getText().toString();
String issuedate = editText3.getText().toString();
String query = "insert into bookrecord(bookname,bookno,issuedate) values('"+bookname+"','"+bookno+"','"+issuedate+"')";
Log.e("query",query);
db.execSQL(query);
Toast.makeText(MainActivity.this, "inserted", Toast.LENGTH_SHORT).show();
}
});
final FragmentManager fragmentManager = getFragmentManager();
final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int i, long id) {
for (int j=0;j<=i;j++){
BookentryFragment bookentryFragment = new BookentryFragment();
fragmentTransaction.replace(android.R.id.content, bookentryFragment);
}
fragmentTransaction.commit();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
HERE IS THE MAIN ACTIVITY XML FILE
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select No. of Books Issued"
android:id="#+id/tv4"
android:layout_centerHorizontal="true"
android:textColor="#color/colorAccent"
android:textSize="19dp"
/>
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/booknoselectspinner"
android:layout_toRightOf="#+id/tv4"
>
</Spinner>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/FM1"
android:layout_below="#+id/tv4"
android:orientation="vertical"
>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save Record"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:id="#+id/button"
android:layout_below="#+id/FM1"
/>
</RelativeLayout>
HERE IS THE FRAGMENT FILE
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:background="#drawable/border">
<EditText
android:layout_width="300dp"
android:layout_height="wrap_content"
android:id="#+id/et1"
android:hint="Enter Book Name"
android:textAlignment="center"
android:layout_centerHorizontal="true"
android:layout_below="#+id/booknoselectspinner"
/>
<EditText
android:layout_width="300dp"
android:layout_height="wrap_content"
android:id="#+id/et2"
android:hint="Enter Book No."
android:textAlignment="center"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:layout_below="#+id/et1"
android:layout_centerHorizontal="true"
/>
<EditText
android:layout_width="300dp"
android:layout_height="wrap_content"
android:id="#+id/et3"
android:inputType="date"
android:hint="Select Issue Date"
android:textAlignment="center"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:layout_below="#+id/et2"
android:layout_centerHorizontal="true"
/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Remind me to Return"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:id="#+id/cb1"
android:layout_below="#+id/et3"
android:layout_centerHorizontal="true"
/>
</RelativeLayout>
LET ME KNOW IF I SHOULD ATTACH SOMETHING ELSE
I TRIED TO USE WHILE LOOP BUT THE APP CRASHES. PLEASE HELP
THANK YOU
I tried it with this Layout Inflater Code.
FrameLayout item = (FrameLayout) findViewById(R.id.FM1);
View child = getLayoutInflater().inflate(R.layout.fragment_bookentry, null);
item.addView(child);
It adds the Fragment once when i open the Activity.
But when i select 2 from the spinner, Nothing Happens.
I am using Switch Case for this Purpose
switch (i) {
case 0:
FrameLayout item = (FrameLayout) findViewById(R.id.FM1);
View child = getLayoutInflater().inflate(R.layout.fragment_bookentry, null);
item.addView(child);
break;
case 1:
FrameLayout item2 = (FrameLayout) findViewById(R.id.FM1);
View child2 = getLayoutInflater().inflate(R.layout.fragment_bookentry, null);
item2.addView(child2);
FrameLayout item3 = (FrameLayout) findViewById(R.id.FM1);
View child3 = getLayoutInflater().inflate(R.layout.fragment_bookentry, null);
item3.addView(child3);
break;
case 2:
FrameLayout item4 = (FrameLayout) findViewById(R.id.FM1);
View child4 = getLayoutInflater().inflate(R.layout.fragment_bookentry, null);
item4.addView(child4);
FrameLayout item5 = (FrameLayout) findViewById(R.id.FM1);
View child5 = getLayoutInflater().inflate(R.layout.fragment_bookentry, null);
item5.addView(child5);
FrameLayout item6 = (FrameLayout) findViewById(R.id.FM1);
View child6 = getLayoutInflater().inflate(R.layout.fragment_bookentry, null);
item6.addView(child6);
break;
}
Make the FrameLayout a class object, and initialize it using (FrameLayout) findViewById(R.id.FM1); only once, outside the switch statement.
In each of your case blocks, add this piece of code in the beginning:
if(item.getChildCount()>0){
item.removeAllViews();
}
EDIT: Your spinner's onItemSelected would be something like:
#Override
public void onItemSelected(AdapterView<?> parent, View view, int i, long id) {
item.removeAllViews();
for (int j=0;j<=i;j++){
View v = getLayoutInflater().inflate(R.layout.fragmentXML, null);
item.addView(v);
}
}

Recyclerview is not displayed in fullscreen

Recyclerview is not displayed in fullscreen. Below is the layout file and the code I've written. After executing, the contents are displayed as shown in the below picture. The height is only the highlighted part. I want the contents to be fullscreen. I remaining contents are within this highlighted area which is scrollable. I want the contents to be displayed in fullscreen. Any help would be helpful.
Layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="#+id/activity_search"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="true"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:clickable="true">
<TextView
android:id="#+id/title"
android:textSize="16dp"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/genre"
android:layout_below="#id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/year"
android:layout_width="wrap_content"
android:layout_alignParentRight="true"
android:layout_height="wrap_content" />
</RelativeLayout>
</LinearLayout>
Code:
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class setSearchData extends RecyclerView.Adapter<setSearchData.MyViewHolder> {
private List<SearchDisplayContents> moviesList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title, year, genre;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
genre = (TextView) view.findViewById(R.id.genre);
year = (TextView) view.findViewById(R.id.year);
}
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.activity_searchresults, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
SearchDisplayContents movie = moviesList.get(position);
holder.title.setText(movie.getTitle());
holder.genre.setText(movie.getGenre());
holder.year.setText(movie.getYear());
}
#Override
public int getItemCount() {
return moviesList.size();
}
}
Calling function code:
List<SearchDisplayContents> movieList = new ArrayList<>();
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
setSearchData mAdapter = new setSearchData(movieList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
SearchDisplayContents movie = new SearchDisplayContents("Mad Max: Fury Road", "Action & Adventure", "2015");
movieList.add(movie);
movie = new SearchDisplayContents("Inside Out", "Animation, Kids & Family", "2015");
movieList.add(movie);
mAdapter.notifyDataSetChanged();
You should use different layout for your viewholder. Take the RelativeLayout you have there, cut it out, put it in different xml file then pass it to onCreateViewHolder.
From look at your code - it looks like what is in the preview screenshot is the same as what is within the RelativeLayout you have staticly defined.
There is an issue with your approach. It is that you are referencing the RelativeLayout (within the same xml hierarchy as your RecylerView) as the CellViewHolder in the RecyclerView.Adapter. My approach personally is to create a seperate xml layout for the cell viewholder.
Follow this guide, it is very detailed:
https://guides.codepath.com/android/using-the-recyclerview
You should use different layout for your viewholder. Take the RelativeLayout you have there, cut it out, put it in different xml file then pass it to onCreateViewHolder.
The above coding has something work use different layout mean one for Recycleview and other for contents in list
main_layout.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"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/uslist"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="#dimen/_49sdp"
android:divider="#android:color/transparent" />
</RelativeLayout>
list_content.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="true"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:clickable="true">
<TextView
android:id="#+id/title"
android:textSize="16dp"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/genre"
android:layout_below="#id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/year"
android:layout_width="wrap_content"
android:layout_alignParentRight="true"
android:layout_height="wrap_content" />
</RelativeLayout>
Adapter.java
public class yourAdapter extends RecyclerView.Adapter<yourAdapter .SimpleViewHolder> {
ArrayList<UsageRPDetails> mylist;
private Context mContext;
public yourAdapter (Context context, ArrayList<yourArray or model> checklist) {
mContext = context;
mylist = checklist;
}
#Override
public yourAdapter .SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_content, parent, false);
return new yourAdapter .SimpleViewHolder(view);
}
#Override
public void onBindViewHolder(final yourAdapter .SimpleViewHolder holder, final int position) {
holder.title.setText();
holder.year.setText();
holder.genre.setText();
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public int getItemCount() {
return mylist.size();
}
#Override
public int getItemViewType(int i) {
return 0;
}
public static class SimpleViewHolder extends RecyclerView.ViewHolder {
#Bind(R.id.title)
TextView title;
#Bind(R.id.genre)
TextView genre;
#Bind(R.id.year)
TextView year;
public SimpleViewHolder(View itemView) {
super(itemView);
title= (TextView) itemView.findViewById(R.id.title);
genre= (TextView) itemView.findViewById(R.id.genre);
genre= (TextView) itemView.findViewById(R.id.genre);
}
}
}
Also write a java file for Activity that calls this adapter class and call the recycleview in this activity

Spinner Item leads to Activity (Android Studio)

I started programming a few month ago and stackoverflow always was a a good dite for solving my problems. So my codes are getting better but now I´m on a point that I Need your help again.
Programm: In my App you can choose items from a spinner, then it goes to next page and so on. You have to choose from several Spinners until you get a result...
Some Code preview (Code works, but i now have to ad some more Action and I don´t know how...
package com.sio.fmf;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Button;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.widget.TextView;
public class Koerperform extends AppCompatActivity {
String[] koerperform = {" ", "spindel- oder torpedoförmig", "langgestreckt", "hochrückig", "schlangenförmig", "welsartig", "grundelartig"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.koerperform);
Spinner mySpinner = (Spinner)findViewById(R.id.spinner);
mySpinner.setAdapter(new MyCustomAdapter(Koerperform.this,R.layout.spinner_layout, koerperform));
}
public void onClick(View v){}
public class MyCustomAdapter extends ArrayAdapter<String> {
public MyCustomAdapter(Context context, int textViewResourceId, String[] objects) {
super(context, textViewResourceId, objects);
}
private Button getSwtitchact;
{
final Button switchact = (Button) findViewById(R.id.button3);
switchact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent act = new Intent(view.getContext(), Maulstellung.class);
startActivity(act);
}
});
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
public View getCustomView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.spinner_layout, parent, false);
TextView label = (TextView) row.findViewById(R.id.koerper);
label.setText(koerperform[position]);
if (position == 0) {
label.setTextColor(0xFFF00000);
}
return row;
}
}
}
So in this state of the app you can choose the string from the spinner and then if you press Botton 3 it changes to class Maulstellung
My Problem: I want that when string "a" is choosen it goes to page xy after Button 3 is pressed and when string "b" is choosen it goes to page xyz after Button 3 is pressed,..., and so on for each string...
Hope you can help me and sorry for my bad English
I will do in this way:
Not sure is this what you need.
Declare String selectedValue and Spinner mySpinner in global(add after line String[] koerperform).
Remove Spinner beside mySpinner:
Spinner mySpinner = (Spinner)findViewById(R.id.spinner);
Inside getSwtitchact, change to this
private Button getSwtitchact;
{
final Button switchact = (Button) findViewById(R.id.button3);
switchact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedValue=mySpinner.getSelectedItem().toString(); // here you get the selected items from spinner
if(selectedValue.equals("a"))
{
Intent act = new Intent(view.getContext(), xy.class);
startActivity(act);
}
else if(selectedValue.equals("B"))
{
Intent act = new Intent(view.getContext(), xyZ.class);
startActivity(act);
}
else
{
......
}
}
});
}
maybe this layout file helps
<pre>
<?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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".Koerperform"
android:background="#023738">
<ImageView
android:layout_width="fill_parent"
android:layout_height="100dp"
android:id="#+id/imageView1"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#drawable/header" />
<ImageView
android:layout_width="400dp"
android:layout_height="100dp"
android:id="#+id/imageView5"
android:background="#drawable/frageeins"
android:layout_below="#+id/space4"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ImageView
android:layout_width="fill_parent"
android:layout_height="120dp"
android:id="#+id/imageView6"
android:background="#drawable/fischeins"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/imageView5" />
<Spinner
android:id="#+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView6"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:clickable="false"
android:contextClickable="false"
/>
<Button
android:layout_width="220dp"
android:layout_height="60dp"
android:id="#+id/button3"
android:layout_marginTop="69dp"
android:background="#drawable/costum_button_weiter_gehts"
android:layout_below="#+id/imageView6"
android:layout_centerHorizontal="true" />
<Space
android:layout_width="30dp"
android:layout_height="20dp"
android:layout_below="#+id/imageView1"
android:layout_centerHorizontal="true"
android:id="#+id/space4" />
</RelativeLayout>

Categories