java.lang.NullPointerException: Android Studio - java

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
I am getting a NullPointerException at line 67 while trying to set a listView with a chat adapter. Here is the class:
I have placed ** around the line I am getting the NullPointerException on. I'm not really understading why its returning as null when I'm setting messageAdapter to a new object of an inner class called ChatAdapter(this).
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
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.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MessageListActivity extends AppCompatActivity {
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
ListView listView;
Button sendButton;
ArrayList<String> arrayList = new ArrayList<String>();
ChatDatabaseHelper Cdb;
private boolean mTwoPane;
ChatAdapter messageAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(getTitle());
listView = (ListView)findViewById(R.id.chatListView);
final EditText editText = (EditText)findViewById(R.id.messageText);
sendButton = (Button)findViewById(R.id.sendButton);
messageAdapter = new ChatAdapter(this); // chatAdapter is a built in adapater
**listView.setAdapter(messageAdapter);**
Cdb = new ChatDatabaseHelper(this);
Cursor cursor = Cdb.getMessages(); // get messages method is of type Cursor from database helper class
// cursor will move through the database to find the next text if there is any.
while (cursor.moveToNext()) { arrayList.add(cursor.getString(cursor.getColumnIndex(Cdb.KEY_MESSAGE))); }
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { // on click listener for the send button
String chatText = editText.getText().toString(); // changing editText to String
arrayList.add(chatText); // adding the string from EditTest to arrayList
boolean isInserted = Cdb.insertData(chatText); // inserting the message text into the database
if(isInserted = true)
{ Toast.makeText(MessageListActivity.this,"Message Sent",Toast.LENGTH_SHORT).show(); } // if the message inserts into the database this toast will show
else {
Toast.makeText(MessageListActivity.this,"Message not Sent",Toast.LENGTH_SHORT).show(); } // if message does not nter the database this toast will show
messageAdapter.notifyDataSetChanged(); // notifying the adapter that a message has been sent, changing from incoming to outgoing
editText.setText(" "); // set the text on the send button to blank.
} // end of onClick view
}); // end of onClickListener
if (findViewById(R.id.message_detail_container) != null) {
// The detail container view will be present only in the
// large-screen layouts (res/values-w900dp).
// If this view is present, then the
// activity should be in two-pane mode.
mTwoPane = true;
}
}
class ChatAdapter extends ArrayAdapter<String> { // custom adapter class // when youc all the adapter it forms the for loop for you.
public ChatAdapter(MessageListActivity ctx) {
super(ctx, 0);
} // default constructor
// method to return the number of rows that will be in your array
// will tell how many times to run a for loop
public int getCount(){ return arrayList.size(); } // will return the size of the array
public String getItem(int position){ return arrayList.get(position); } // will return the item at position
// getview method
#Override
public View getView(int position, final View convertView, ViewGroup parent) {// inner class
LayoutInflater Inflater = MessageListActivity.this.getLayoutInflater(); // an inflater inflates the xml layout into a view.
View result = null;
if(position%2 == 0){ // if position number in the array is odd do this, if number is even, do this.
result = Inflater.inflate(R.layout.chat_row_incoming, null); // depending on the position, show layout incoming
} else {
result = Inflater.inflate(R.layout.chat_row_outgoing,null); // depending on the position, show layout outgoing
}
TextView message = (TextView)result.findViewById(R.id.messageText); // creating a message of type TextView connected to messageText
final String messageText = getItem(position) ;
message.setText(messageText);
result.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(MessageDetailFragment.ARG_ITEM_ID,messageText );
MessageDetailFragment fragment = new MessageDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.message_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, MessageDetailActivity.class);
intent.putExtra(MessageDetailFragment.ARG_ITEM_ID,messageText );
context.startActivity(intent);
}
}
});
return result; // return the view which is the Inflater.
}
} // end of chat adapter class
private void setupRecyclerView(#NonNull RecyclerView recyclerView) {
recyclerView.setAdapter(new SimpleItemRecyclerViewAdapter(DummyContent.ITEMS));
}
public class SimpleItemRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {
private final List<DummyContent.DummyItem> mValues;
public SimpleItemRecyclerViewAdapter(List<DummyContent.DummyItem> items) {
mValues = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.message_list_content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.mIdView.setText(mValues.get(position).id);
holder.mContentView.setText(mValues.get(position).content);
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(MessageDetailFragment.ARG_ITEM_ID, holder.mItem.id);
MessageDetailFragment fragment = new MessageDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.message_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, MessageDetailActivity.class);
intent.putExtra(MessageDetailFragment.ARG_ITEM_ID, holder.mItem.id);
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public DummyContent.DummyItem mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.id);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.ChatWindow">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/chatListView"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="false"
android:layout_alignWithParentIfMissing="false"
android:layout_above="#+id/sendButton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/sendButton"
android:id="#+id/sendButton"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:singleLine="true" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/messageText"
android:layout_toStartOf="#id/sendButton"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:enabled="true"
/>
</RelativeLayout>

just try
messageAdapter = new ChatAdapter(MessageListActivity .this);

Related

How to start a new activity when item is clicked of a custom list view

I am trying to start new activity when I select an item of a custom list view, I tried the app on emulator and the new activity is not started and the item was not clickable...!. Why the item is not clickable ? any idea ? any suggestion ?
The following is the activity that uses a custom list view:
package com.example.welcome.madrasti;
import android.content.Intent;
import android.database.Cursor;
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.ListView;
import java.util.ArrayList;
import java.util.List;
public class ListOfSchoolsPublic extends AppCompatActivity {
Intent redirect;
Intent item;
ListView list;
ArrayList<String> _sa;
DBAdapter db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_of_schools_public);
openDB();
list= (ListView) findViewById(R.id.usersList);
redirect = getIntent();
Cursor cursor = db.getAllRows();
_sa= new ArrayList<String>();
//cursor.moveToFirst();
Log.d("CURSORCOUNT","Number of rows in the Cursor is = " + String.valueOf(cursor.getCount()));
while(cursor.moveToNext()) {
if(cursor.getString(DBAdapter.COL_SChOOL_TYPE_TABLE_2).equals("حكومية"))
_sa.add(cursor.getString(DBAdapter.COL_SCHOOLNAME_TABLE_2));
}
cursor.close();
#SuppressWarnings("rawtypes")
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,_sa);
list.setAdapter(new TempLyaout(ListOfSchoolsPublic.this,_sa));
list.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
String selectedItem = (String) arg0.getItemAtPosition(position);
itemInfo(selectedItem);
}
});
}
///////////////////////////////////////////////////////////////
public void itemInfo(String selectedItem){
item = new Intent(getApplicationContext(), NewSchool.class);
item.putExtra("schoolName",selectedItem);
startActivity(item);
}
///////////////////////////////////////////////////////////////
#Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}// end onDestroy method
///////////////////////////////////////////////////////////////
private void openDB() {
db = new DBAdapter(ListOfSchoolsPublic.this);
db.open();
} // end openDB method
//////////////////////////////////////////////////////////////
private void closeDB() {
db.close();
} // end closeDB method
}
The following is the xml of the list view:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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=".ListOfSchoolsPublic">
<ListView
android:id="#+id/usersList"
android:layout_width="395dp"
android:layout_height="523dp"
android:focusable="false"
android:layout_x="4dp"
android:layout_y="-1dp"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="7dp"></ListView>
</android.support.constraint.ConstraintLayout>
This issue presist when you have some clickable item in your list item.
If your item listener is not working then you can apply this on ListView in xml layout.
android:descendantFocusability="blocksDescendants"
You can also put many clicks listeners if you need in adapter class like
public class MyAdapter extends ArrayAdapter<Contact> {
Context context;
public MyAdapter(Context context, ArrayList<Contact> users) {
super(context, 0, users);
this.context = context;
}
public View getView(int position, View convertView, ViewGroup parent) {
Contact user = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.listviewadapter, parent, false);
}
TextView name = convertView.findViewById(R.id.name);
TextView num = convertView.findViewById(R.id.num);
// Populate the data into the template view using the data object
name.setText(user.name);
num.setText(user.phone_number);
// can set click on name or num
name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, position + "position clicked", Toast.LENGTH_SHORT).show();
}
});
// can set click on full list item
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, position + "position clicked", Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
}

OnCreateView method in Activity class

fragment reminder image - current problem
This current class that I am using called Fragment Reminder is used to display a list of the medications that have been entered. However this class before was a Fragment and I decided to change it to an Activity and the method which displays the list called onCreateView is unused now. When I click on that button to run this class the screen goes dark for some reason. Now that this class is an Activity the onCreateView cannot be used since that is for a Fragment. What should I change that to so I can create the list.
FragmentReminder:
package com.example.junai.mrtest2;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import static android.view.View.GONE;
public class FragmentReminder extends Activity implements View.OnClickListener{
private ArrayList al;
private List list=new ArrayList();
private ArrayAdapter<String> adapter;
ListView lv;
TextView tv;
FloatingActionButton fab;
public void receiveData(ArrayList al)
{
this.al=al;
list.add(al.get(0));
}
//data for customlist
private String desc[] = {};
// #Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.setTitle("Medicine Reminder");
View v=inflater.inflate(R.layout.fragment_reminder, container, false);
fab=(FloatingActionButton)v.findViewById(R.id.floatingActionButton);
lv=(ListView)v.findViewById(R.id.rem_lv);
tv=(TextView) v.findViewById(R.id.reminder_tv);
fab.setOnClickListener(this);
DatabaseHandler db=new DatabaseHandler(this);
list=db.getAllReminders();
if(list.size()==0)
{
lv.setVisibility(GONE);
return v;
}
tv.setVisibility(GONE);
adapter = new CustomList(this,list,desc);
lv.setAdapter(adapter);
//***Customised list view add***********************************************************************
/* CustomList customList = new CustomList(getActivity(),list, desc);
lv.setAdapter(customList);*/
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//Toast.makeText(getActivity(),"You Clicked "+list.get(i),Toast.LENGTH_SHORT).show();
//addReminderInCalendar();
Intent in=new Intent(FragmentReminder.this,MedRemInfo.class);
in.putExtra("id",list.get(i).toString());
startActivity(in);
}
});
//***************************************************************************
return v;
}
#Override
public void onClick(View v) {
Intent in=new Intent(this,AddReminder.class);
startActivity(in);
}
}
fragment_reminder.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.junai.mrtest2.FragmentReminder">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="20dp"
android:id="#+id/reminder_tv"
android:textSize="20dp"
android:text="No Reminders to show, Add a reminder.."
android:gravity="center"
/>
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:src="#drawable/ic_add_black_24dp"
android:tint="#ffffff"
android:layout_gravity="bottom|center"
android:id="#+id/floatingActionButton" />
<ListView
android:layout_width="match_parent"
android:id="#+id/rem_lv"
android:layout_height="match_parent"
/>
</LinearLayout>
MainActivity:
package com.example.junai.mrtest2;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
/**
* Created by junai on 20/03/2018.
*/
public class MainActivity extends Activity {
private Button btn_addReminder, btn_reminderinfo;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_addReminder = (Button) findViewById(R.id.btn_addReminder);
btn_addReminder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, AddReminder.class));
}
});
btn_reminderinfo = (Button) findViewById(R.id.btn_reminderinfo);
btn_reminderinfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, FragmentReminder.class));
}
});
}
}
CustomList:
package com.example.junai.mrtest2;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.Typeface;
import android.util.Log;
import android.util.TypedValue;
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.List;
import java.util.Random;
public class CustomList extends ArrayAdapter<String> {
private List names;
private String[] desc;
private Activity context;
public CustomList(Activity context, List names, String[] desc) {
super(context, R.layout.list_medinfo, names);
this.context = context;
this.names = names;
this.desc = desc;
}
String color_hex[]={"#ff4000","#0000ff","#003EFF","#5C246E","#8B668B","#CD2990","#D41A1F","#FBDB0C","#FF6600"};
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//********************************************************************
ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
// If holder not exist then locate all view from UI file.
if (convertView == null) {
// inflate UI from XML file
convertView = inflater.inflate(R.layout.list_medinfo, parent, false);
// get all UI view
holder = new ViewHolder(convertView);
// set tag for holder
convertView.setTag(holder);
} else {
// if holder created, get tag from view
holder = (ViewHolder) convertView.getTag();
}
holder.textView.setText(getItem(position));
String firstLetter = null;
//get first letter of each String item
Log.d("String",getItem(position));
String str=getItem(position);
firstLetter=String.valueOf(str.charAt(0)).toUpperCase();
// firstLetter.toUpperCase();
ColorGenerator generator = ColorGenerator.MATERIAL; // or use DEFAULT
// generate random color
//int color = generator.getColor(getItem(position));
int color = generator.getRandomColor();
int pos= new Random().nextInt(color_hex.length);
color = Color.parseColor(color_hex[pos]);
Log.d("Color",""+pos);
TextDrawable drawable = TextDrawable.builder()
.buildRound(firstLetter, color); // radius in px
holder.imageView.setImageDrawable(drawable);
return convertView;
//***********************************************************************
/* LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.list_medinfo, null, true);
TextView textViewName = (TextView) listViewItem.findViewById(R.id.medname);
TextView textViewDesc = (TextView) listViewItem.findViewById(R.id.textViewDesc);
ImageView image = (ImageView) listViewItem.findViewById(R.id.imageView);
textViewName.setText(names.get(position).toString());
textViewDesc.setText(desc[position]);
image.setImageResource(imageid[position]);
return listViewItem;*/
}
private class ViewHolder {
private ImageView imageView;
private TextView textView;
public ViewHolder(View v) {
imageView = (ImageView) v.findViewById(R.id.medimage);
textView = (TextView) v.findViewById(R.id.medname);
Typeface typeface=Typeface.createFromAsset(context.getAssets(), "fonts/georgia.ttf");
textView.setTypeface(typeface);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP,20);
}
}
}
I've refactored your code:
public class FragmentReminder extends Activity implements View.OnClickListener {
private ArrayList al;
private List list = new ArrayList();
private ArrayAdapter<String> adapter;
ListView lv;
TextView tv;
FloatingActionButton fab;
public void receiveData(ArrayList al) {
this.al = al;
list.add(al.get(0));
}
//data for customlist
private String desc[] = {};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_reminder);
fab = (FloatingActionButton) findViewById(R.id.floatingActionButton);
lv = (ListView) findViewById(R.id.rem_lv);
tv = (TextView) findViewById(R.id.reminder_tv);
fab.setOnClickListener(this);
DatabaseHandler db = new DatabaseHandler(this);
list = db.getAllReminders();
if (list.size() == 0) {
lv.setVisibility(GONE);
}
tv.setVisibility(GONE);
adapter = new CustomList(this, list, desc);
lv.setAdapter(adapter);
//***Customised list view add***********************************************************************
/* CustomList customList = new CustomList(getActivity(),list, desc);
lv.setAdapter(customList);*/
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//Toast.makeText(getActivity(),"You Clicked "+list.get(i),Toast.LENGTH_SHORT).show();
//addReminderInCalendar();
Intent in = new Intent(FragmentReminder.this, MedRemInfo.class);
in.putExtra("id", list.get(i).toString());
startActivity(in);
}
});
}
#Override
public void onClick(View v) {
Intent in = new Intent(this, AddReminder.class);
startActivity(in);
}
}
You need only to move the code to onCreate() instead of onCreateView() and also you don't need to access the recently inflated view V to do findViewByID, all you have to do is setContentView() beforehand.

How to programmatically Next and Prev buttons for Master / Detail flow

I have created a sample app using the "Master / Detail flow" activity. I have added two buttons, Next and Prev to the detail activity. How to I set programmatically the buttons actions instead having to go back and forth between the List and detail?
item_detail.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="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingStart="30dp"
android:paddingEnd="30dp"
android:weightSum="4"
android:gravity="end"
android:orientation="horizontal">
<Button
android:id="#+id/button_prev"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Prev"/>
<Button
android:id="#+id/button_next"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Next"/>
</LinearLayout>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/item_detail"
style="?android:attr/textAppearanceLarge"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:textIsSelectable="true"
tools:context="co.test.app.sample.itemapplication.ItemDetailFragment"/>
</LinearLayout>
activity_item_detail.xml
<android.support.design.widget.CoordinatorLayout 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"
android:fitsSystemWindows="true"
tools:context="co.test.app.sample.itemapplication.ItemDetailActivity"
tools:ignore="MergeRootFrame">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="#dimen/app_bar_height"
android:fitsSystemWindows="true"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:toolbarId="#+id/toolbar">
<android.support.v7.widget.Toolbar
android:id="#+id/detail_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"/>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:id="#+id/item_detail_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
DummyContent.java
package co.test.app.sample.itemapplication.dummy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Helper class for providing sample content for user interfaces created by
* Android template wizards.
* <p>
* TODO: Replace all uses of this class before publishing your app.
*/
public class DummyContent {
/**
* An array of sample (dummy) items.
*/
public static final List<DummyItem> ITEMS = new ArrayList<DummyItem>();
/**
* A map of sample (dummy) items, by ID.
*/
public static final Map<String, DummyItem> ITEM_MAP = new HashMap<String, DummyItem>();
private static final int COUNT = 25;
static {
// Add some sample items.
for (int i = 1; i <= COUNT; i++) {
addItem(createDummyItem(i));
}
}
private static void addItem(DummyItem item) {
ITEMS.add(item);
ITEM_MAP.put(item.id, item);
}
private static DummyItem createDummyItem(int position) {
return new DummyItem(String.valueOf(position), "Item " + position, makeDetails(position));
}
private static String makeDetails(int position) {
StringBuilder builder = new StringBuilder();
builder.append("Details about Item: ").append(position);
for (int i = 0; i < position; i++) {
builder.append("\nMore details information here.");
}
return builder.toString();
}
/**
* A dummy item representing a piece of content.
*/
public static class DummyItem {
public final String id;
public final String content;
public final String details;
public DummyItem(String id, String content, String details) {
this.id = id;
this.content = content;
this.details = details;
}
#Override
public String toString() {
return content;
}
}
}
ItemDetailActivity.java
package co.test.app.sample.itemapplication;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.ActionBar;
import android.view.MenuItem;
/**
* An activity representing a single Item detail screen. This
* activity is only used narrow width devices. On tablet-size devices,
* item details are presented side-by-side with a list of items
* in a {#link ItemListActivity}.
*/
public class ItemDetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.detail_toolbar);
setSupportActionBar(toolbar);
// Show the Up button in the action bar.
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
// savedInstanceState is non-null when there is fragment state
// saved from previous configurations of this activity
// (e.g. when rotating the screen from portrait to landscape).
// In this case, the fragment will automatically be re-added
// to its container so we don't need to manually add it.
// For more information, see the Fragments API guide at:
//
// http://developer.android.com/guide/components/fragments.html
//
if (savedInstanceState == null) {
// Create the detail fragment and add it to the activity
// using a fragment transaction.
Bundle arguments = new Bundle();
arguments.putString(ItemDetailFragment.ARG_ITEM_ID,
getIntent().getStringExtra(ItemDetailFragment.ARG_ITEM_ID));
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.add(R.id.item_detail_container, fragment)
.commit();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
navigateUpTo(new Intent(this, ItemListActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
ItemListActivity.java
package co.test.app.sample.itemapplication;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import co.test.app.sample.itemapplication.dummy.DummyContent;
import java.util.List;
/**
* An activity representing a list of Items. This activity
* has different presentations for handset and tablet-size devices. On
* handsets, the activity presents a list of items, which when touched,
* lead to a {#link ItemDetailActivity} representing
* item details. On tablets, the activity presents the list of items and
* item details side-by-side using two vertical panes.
*/
public class ItemListActivity extends AppCompatActivity {
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
private boolean mTwoPane;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(getTitle());
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
View recyclerView = findViewById(R.id.item_list);
assert recyclerView != null;
setupRecyclerView((RecyclerView) recyclerView);
if (findViewById(R.id.item_detail_container) != null) {
// The detail container view will be present only in the
// large-screen layouts (res/values-w900dp).
// If this view is present, then the
// activity should be in two-pane mode.
mTwoPane = true;
}
}
private void setupRecyclerView(#NonNull RecyclerView recyclerView) {
recyclerView.setAdapter(new SimpleItemRecyclerViewAdapter(DummyContent.ITEMS));
}
public class SimpleItemRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {
private final List<DummyContent.DummyItem> mValues;
public SimpleItemRecyclerViewAdapter(List<DummyContent.DummyItem> items) {
mValues = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_list_content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.mIdView.setText(mValues.get(position).id);
holder.mContentView.setText(mValues.get(position).content);
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.id);
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, ItemDetailActivity.class);
intent.putExtra(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.id);
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public DummyContent.DummyItem mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.id);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
}
This is the code snippet used to forward to the detail page.
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.id);
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.item_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, ItemDetailActivity.class);
intent.putExtra(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.id);
context.startActivity(intent);
}
You can forward to any page by changing the value of arguments.putString(ItemDetailFragment.ARG_ITEM_ID, holder.mItem.id);
Use the above snippets in the onClick events of next and prev buttons. cheers :)

Expandable Listview OnClickListeners

I am creating an app in android studios that requires the user to select a child item from an expandable listview on one activity and for it to be displayed on another activity. I'm new to java and android studios and still dont understand how to do this really. If anyone has any sample code or can help that would be great, thanks!
You should use the setOnChildClickListener method from the ExpandableListView class to create a ClickListener for the list elements and then use a Intent to open the new activity. The call to set the listener should be set after you've set the adapter for the ListView.
Here there's a tutorial for using a ExpandableListView and it shows how to set a ClickListener for the elements.
And here there's the Android developer's documentation which shows how to create and open a new Activity from a button's click.
**You should use the setOnChildClickListener method from the ExpandableListView class to create a ClickListener for the list elements and then use a Intent to open the new activity. The call to set the listener should be set after you've set the adapter for the ListView and create the xml file for child and parent.child will be Expandable TextView **
**layout file**
<?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.elite_android.explistview1.MainActivity">
<RelativeLayout
android:id="#+id/main_number_picker_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="17dp">
<NumberPicker
android:id="#+id/main_number_picker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="Next" />
<TextView
android:id="#+id/main_txt_patient_count"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toLeftOf="#id/main_number_picker"
android:text="Select number of patient"
android:textColor="#color/colorAccent"
android:layout_marginLeft="80dp"/>
</RelativeLayout>
<ExpandableListView
android:id="#+id/exp_Listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/main_number_picker_layout">
</ExpandableListView>
</RelativeLayout>
**Main Activity.java file**
package com.example.elite_android.explistview1;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.view.View.OnFocusChangeListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ListView;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.NumberPicker;
public class MainActivity extends AppCompatActivity {
ExpandableListView expandableListView;
private MyAdapter mAdapter;
ExpandableListView expand;
NumberPicker numberPicker;
private List<String> headerItems;
private ArrayList childDetails;
private HashMap<String, List<String>> childList;
private Context ctx;
EditText editText1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get reference to the EditText
editText1 = (EditText) findViewById(R.id.child_item);
// //set the onFocusChange listener
// // editText1.setOnFocusChangeListener(editText1.getOnFocusChangeListener());
//
//// //get reference to EditText
//// editText2 = (EditText) findViewById(R.id.sequence);
//// // set the on focusChange listner
//// editText2.setOnFocusChangeListener(editText2.getOnFocusChangeListener());
//
// //Generate list View from ArrayList;
//
//
// EditText editText = (EditText) findViewById(R.id.child_item);
// editText.requestFocus();
// InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
//
//
//// editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
// // #Override
// // public void onFocusChange(View v, boolean hasFocus) {
// // //editText.setOnFocusChangeListener();
// // return;
// // }
// //});
//
String[] numbers = new String[10];
for (int count = 0; count < 10; count++)
numbers[count] = String.valueOf(count);
numberPicker = (NumberPicker) findViewById(R.id.main_number_picker);
numberPicker.setMaxValue(numbers.length);
numberPicker.setMinValue(1);
numberPicker.setDisplayedValues(numbers);
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
generateListItems(newVal);
loadRecycleView();
}
});
}
private void generateListItems(int childCount) {
if (headerItems != null)
headerItems.clear();
else
headerItems = new ArrayList<>();
if (childList != null)
childList.clear();
else
childList = new HashMap();
if (childDetails == null) {
childDetails = new ArrayList();
childDetails.add("Name");
childDetails.add("Age");
childDetails.add("Gender");
}
// Put header items
for (int count = 0; count < childCount; count++) {
headerItems.add(" Parent " + count);
childList.put(headerItems.get(count), childDetails);
}
}
private void loadRecycleView() {
if (expandableListView == null) {
expandableListView = (ExpandableListView) findViewById(R.id.exp_Listview);
mAdapter = new MyAdapter(this, headerItems, childList);
expandableListView.setAdapter(mAdapter);
} else {
expandableListView.invalidate();
mAdapter.setHeaderData(headerItems);
mAdapter.setListData(childList);
mAdapter.notifyDataSetChanged();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
}
**Adapter class.java**
package com.example.elite_android.explistview1;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.widget.EditText;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.view.View.OnFocusChangeListener;
/**
* Created by ELITE-ANDROID on 28-02-2017.
*/
// this is provides all needs methods implementing an Expandable List VIew
public class MyAdapter extends BaseExpandableListAdapter {
// We need some Variables here so therer are some Variables here
private List<String> header_titles; // This is for Representing the HeadLine(Array list)
private HashMap<String, List<String>> child_titles; // defin the HashMap for the child item how to Represent the Parent Handing so Hash Map, need some Variables
private Context ctx;
private NumberPicker numberPicker;
EditText editText;
View view;
private static LayoutInflater inflater = null;
//for initalized for all Variables we need some Constructor
public MyAdapter(Context context, List<String> header_titles, HashMap<String, List<String>> child_titles) {
super();
this.ctx = context;
this.child_titles = child_titles;
this.header_titles = header_titles;
}
public void refreshHeader_titles(List<String> events) {
this.header_titles.clear();
this.header_titles.addAll(header_titles);
notifyDataSetChanged();
}
;
#Override
// From this Override method How to Return how many elements are the Group count like parent
public int getGroupCount() {
return header_titles.size();
}
#Override
//here the number of child items are in each heading. There are three Heading - PAtien Name ,Age, Gender
public int getChildrenCount(int groupPosition) {
// Log.d("xxx", )
return child_titles.get(header_titles.get(groupPosition)).size(); //how to Return the size of HashMap
}
#Override
public Object getGroup(int groupPosition) {
return header_titles.get(groupPosition);
}
#Override
// here how to retuen child items on the particular headings and Positions.
public Object getChild(int groupPosition, int childPosition) {
return child_titles.get(header_titles.get(groupPosition)).get(childPosition);
}
#Override
//return the groupo position
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
// Here return the Group View
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
// ListViewHolder viewHolder;
// if (view == null) {
// viewHolder = new ListViewHolder();
// LayoutInflater inflater = context.getLayoutInflater();
// view = inflater.inflate(R.layout.listitems, null, true);
// viewHolder.itmName = (TextView) view.findViewById(R.id.Item_name);
// viewHolder.itmPrice = (EditText) view.findViewById(R.id.Item_price);
// view.setTag(viewHolder);
// } else {
// viewHolder = (ListViewHolder) view.getTag();
//// loadSavedValues();
// }
// Here how to get the Heading Title here Decalered String Variables, now how to get title of heading from getGroup methods so simple call Backed Methods.
String title = (String) this.getGroup(groupPosition);
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.prent, null);
}
TextView textView = (TextView) convertView.findViewById(R.id.heading_item);
textView.setText(title); // for Heading bold style ,title
return convertView;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
String title = (String) this.getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.child, null);
}
String cellData = child_titles.get(header_titles.get(groupPosition)).get(childPosition);
EditText childItem = (EditText) convertView.findViewById(R.id.child_item);
childItem.setHint(cellData);
childItem.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// Log.d("xxxx", "Has focus " + hasFocus);
if (!hasFocus) {
// int itemIndex = View.getId();
// String enteredName = ((EditText)v).getText().toString();
// selttems.put(itemIndex, enteredName);
} else {
}
return;
}
});
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public void setListData(HashMap<String, List<String>> lData) {
child_titles = lData;
}
public void setHeaderData(List<String> hData) {
header_titles = hData;
}
}
**child.Xml file**
<?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="50dp"
android:background="#ffff">
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/child_item"
android:textSize="25dp"
android:textStyle="bold"
android:gravity="center_vertical"
android:layout_marginLeft="10dp"/>
<!--<EditText-->
<!--android:id="#+id/sequence"-->
<!--android:layout_width="wrap_content"-->
<!--android:layout_height="wrap_content"-->
<!--android:layout_alignParentLeft="true"-->
<!--android:layout_alignParentTop="true"-->
<!--android:paddingLeft="35sp"-->
<!--android:layout_marginRight="10dp"-->
<!--android:textAppearance="?android:attr/textAppearanceMedium" />-->
</LinearLayout>
<!--This Layout File Represent the Child Items.
This Field Represent the Child Item IN the List VIew -->
**parent.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="50dp"
android:orientation="vertical">
<TextView
android:id="#+id/heading_item"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:gravity="center_vertical"
android:textColor="#color/colorAccent"
android:textSize="25dp" />
</LinearLayout>
<!--This Layout file for Heading -Lines.-->

Countdown timers in a ListView

I have a ListView with the name of the timer, and the time of the timer, I don't know how to implement the countdown part. In each row in the ListView I have two TextViews: the time and the name of the timer, and then a Button which should start and stop the timer. This is my custom ListViewAdapter class, where I believe the timer should start stop in the OnClick method, to have the timer reacting to each line:
public class CustomTimerRowAdapter extends ArrayAdapter<TimerRow> {
Context context;
int height;
public CustomTimerRowAdapter(Context context, int resourceId,
List<TimerRow> items) {
super(context, resourceId, items);
this.context = context;
// Height of screen from not Activity subclass
height = context.getResources().getDisplayMetrics().heightPixels;
}
/* private view holder class */
private class ViewHolder {
TextView txtTimer;
TextView txtName;
Button bStartStop;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
TimerRow rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.timer_row, null);
holder = new ViewHolder();
// make layout params
holder.txtTimer = (TextView) convertView.findViewById(R.id.tvTimes);
holder.txtTimer.getLayoutParams().height = height / 10;
holder.txtName = (TextView) convertView.findViewById(R.id.tvName);
holder.txtName.getLayoutParams().height = height / 10;
holder.bStartStop = (Button) convertView
.findViewById(R.id.bStartStopTimer);
holder.bStartStop.getLayoutParams().height = height / 10;
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtName.setText(rowItem.getName());
holder.txtTimer.setText(rowItem.getTimer());
final String name = holder.txtName.getText().toString();
holder.bStartStop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// THIS IS WHERE THE TIMER SHOULD START AND STOP.
Toast.makeText(context, "Selected " + name + " timer.",
Toast.LENGTH_SHORT).show();
}
});
return convertView;
}
}
The length of the timers can be up to 99 hours, 59 minutes and 59 seconds. The timers are formatted as strings like this "hh:mm:ss".
Please use RecyclerView instead of Listview. Here you can check and download the source code of Countdown timers in a ListView
activity_main.xml
<RelativeLayout 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>
adapter_layout.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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp"
android:padding="10dp"
android:id="#+id/tv_timer"/>
</LinearLayout>
MainActivity.java
package com.androidsolutionworld.multipletimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.LinearLayout;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private ArrayList al_data = new ArrayList<>();
private Adapter obj_adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView)findViewById(R.id.recycler_view);
al_data.add("1234");
al_data.add("1257");
al_data.add("100");
al_data.add("1547");
al_data.add("200");
al_data.add("500");
al_data.add("2000");
al_data.add("1000");
obj_adapter = new Adapter(al_data);
LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.VERTICAL,false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(obj_adapter);
}
}
Custom Adapter:
import android.os.CountDownTimer;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
public class Adapter extends RecyclerView.Adapter{
private ArrayList al_data;
public class MyViewHolder extends RecyclerView.ViewHolder{
public TextView tv_timer;
CountDownTimer timer;
public MyViewHolder (View view){
super(view);
tv_timer = (TextView)view.findViewById(R.id.tv_timer);
}
}
public Adapter(ArrayList al_data) {
this.al_data = al_data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_layout,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
holder.tv_timer.setText(al_data.get(position));
if (holder.timer != null) {
holder.timer.cancel();
}
long timer = Long.parseLong(al_data.get(position));
timer = timer*1000;
holder.timer = new CountDownTimer(timer, 1000) {
public void onTick(long millisUntilFinished) {
holder.tv_timer.setText("" + millisUntilFinished/1000 + " Sec");
}
public void onFinish() {
holder.tv_timer.setText("00:00:00");
}
}.start();
}
#Override
public int getItemCount() {
return al_data.size();
}
}

Categories

Resources