OnCreateView method in Activity class - java

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.

Related

Listview button click listener is not working

I'm using an adapter class to set values for my items. For each item there is a + and a - button. I have a foodActivity java class, activity_food layout for the java class and a list_view_layout for the lists. I have initialized the + and - buttons inside my activity class. When the activity_food starts, the app crashes.
plus, minus and edittext in list_view_layout -
<Button
android:id="#+id/minus"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_below="#+id/foodname"
android:layout_toEndOf="#+id/foodpic"
android:text="-"
android:textSize="12sp" />
<EditText
android:id="#+id/quantity"
android:layout_width="25dp"
android:layout_height="30dp"
android:layout_below="#+id/foodname"
android:layout_toEndOf="#+id/minus"
android:ems="10"
android:inputType="number"
android:textAlignment="center"
android:background="#drawable/edittextbackground"
android:text="0" />
<Button
android:id="#+id/plus"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_alignTop="#+id/quantity"
android:layout_toEndOf="#+id/quantity"
android:text="+"
android:textSize="12sp" />
activity_food layout -
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.res.easyorder.foodActivity">
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:divider="#ffff"
android:dividerHeight="5dp"/>
</RelativeLayout>
My adapter class -
package com.res.easyorder;
import android.content.Context;
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.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.zip.Inflater;
public class MyAdapter extends ArrayAdapter<item> {
int q_ty = 0;
ArrayList<item> foodlist = new ArrayList<>();
public MyAdapter(Context context, int textViewResourceId, ArrayList<item> objects){
super(context, textViewResourceId, objects);
foodlist = objects;
}
#Override
public int getCount(){
return super.getCount();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent){
View v = convertView;
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.list_view_layout, null);
ImageView foodpic = (ImageView) v.findViewById(R.id.foodpic);
TextView foodname = (TextView) v.findViewById(R.id.foodname);
TextView foodprice = (TextView) v.findViewById(R.id.foodprice);
Button plus = (Button) v.findViewById(R.id.plus);
final EditText quantity = (EditText) v.findViewById(R.id.quantity);
Button minus = (Button) v.findViewById(R.id.minus);
plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
item item = getItem(position);
q_ty = Integer.parseInt(item.getQuantity());
q_ty = q_ty + 1;
quantity.setText("" +q_ty);
}
});
foodname.setText(foodlist.get(position).getFoodName());
foodpic.setImageResource(foodlist.get(position).getFoodImage());
foodprice.setText("BDT: " +foodlist.get(position).getFoodPrice());
quantity.setText(foodlist.get(position).getQuantity());
return v;
}
}
foodActivity java code. Plus minus onclicklistener is being commented -
package com.res.easyorder;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import java.util.ArrayList;
public class foodActivity extends AppCompatActivity {
private String type = null;
int quantity = 0;
private Button plus, minus;
private EditText q_ty;
ListView simplelist;
ArrayList<item> foodlist = new ArrayList<>();
private FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_food);
firebaseAuth = FirebaseAuth.getInstance();
simplelist = (ListView) findViewById(R.id.listview);
plus = (Button) findViewById(R.id.plus);
minus = (Button) findViewById(R.id.minus);
q_ty = (EditText) findViewById(R.id.quantity);
type = getIntent().getExtras().getString("type");
if(type.equals("breakfast"))
{
foodlist.add(new item("Rooti",R.drawable.ruti,5));
foodlist.add(new item("Parata",R.drawable.porata,8));
foodlist.add(new item("Tandoor",R.drawable.tandoor,15));
foodlist.add(new item("Vegetable",R.drawable.sodji,10));
foodlist.add(new item("Daal",R.drawable.dal,10));
foodlist.add(new item("Omelet",R.drawable.dimvaji,15));
foodlist.add(new item("Singara",R.drawable.singara,8));
foodlist.add(new item("Samosa",R.drawable.samosa,10));
foodlist.add(new item("Puri",R.drawable.puri,5));
}
MyAdapter myAdapter = new MyAdapter(this,R.layout.list_view_layout,foodlist);
simplelist.setAdapter(myAdapter);
/*plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//quantity = quantity + 1;
//q_ty.setText(""+quantity);
}
});
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (quantity==0)
{
//q_ty.setText(""+quantity);
}
else if (quantity>0)
{
quantity = quantity - 1;
//q_ty.setText(""+quantity);
}
}
});*/
}
}
You are facing this problem because you have plus minus button on Listview item row xml file and you are finding plus minus button in activity. You have to put your click listener in your adapter class
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_entry, null);
holder = new ViewHolder();
holder.quantity= (EditText) convertView.findViewById(R.id.quantity);
holder.plus = (Button) convertView.findViewById(R.id.plus);
holder.minus = (Button) convertView.findViewById(R.id.minus);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
Item item = getItem(position);
holder.quantity.setText(item.getQuantity());
holder.plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Item item = getItem(position);
q_ty = Integer.parseInt(item.getQuantity());
q_ty = q_ty + 1;
quantity.setText("" +q_ty);
item.setQuantity(q_ty);
}
});
return convertView;
}
You have to set the OnClicklistener in your "MyAdapter.getView(..)" method, because in this method the items are created. Currently in your foodActivity.onCreate() methode the objects plus, minus and q_ty are null.

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

Full image adapter error

I have a custom base image adapter in which i use for a grid view.. i was trying to use it for a full image view but i get an error while creating the my custom adapter object...passing the parameters....
By the way sorry for any mistakes ,this is my first question:
This is for gallery to preview full
Fullimage java:Where the error is present
public class FullImage extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_image);
Intent i= getIntent();
int position = i.getExtras().getInt("id");
MyPicsAdapter adapter = new MyPicsAdapter(this);//ERROR is here!!!
ImageView imageView = (ImageView) findViewById(R.id.fullimage);
imageView.setImageResource(adapter.item_image[position]);
}
}
Custom Adapter:
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MyPicsAdapter extends BaseAdapter{
public Context context;
public final int item_image[];
public final String item_text[];
public MyPicsAdapter(Context context, int item_image[], String[] item_text)
{
this.context = context;
this.item_image = item_image;
this.item_text = item_text;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(context);
// get layout from custom_gridview.xml
gridView = inflater.inflate(R.layout.custom_gridview, null);
// set value into imageview
ImageView image = (ImageView) gridView.findViewById(R.id.item_image);
image.setImageResource(item_image[position]);
// set value into textview
TextView text = (TextView) gridView.findViewById(R.id.item_text);
text.setText(item_text[position]);
} else {
gridView = (View) convertView;
}
return gridView;
}
#Override
public int getCount() {
return item_text.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
}
Class where the images are:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
public class Smitpic extends AppCompatActivity {
GridView grid;
String text[] = {
"Colorful countryside on the way to Smit",
"A local bus at the Village square",
"Cattle grazing at the village ground",
"Pine trees lined the road leading to the Wooden house",
"Traditional wooden house made without any metal nails",
"Intricate carvings on the door of the wooden house",
"A cottage at Smit",
"Villagers returning home after washing clothes at the river",
"A river idlying flowing near Smit",
"Colorful field of grasses and pine trees"
};
int image[] = {R.drawable.smit1,R.drawable.smit2,
R.drawable.smit3,R.drawable.smit4,R.drawable.smit5,
R.drawable.smit6,R.drawable.smit7,R.drawable.smit8,
R.drawable.smit9,R.drawable.smit10
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_smitpic);
grid = (GridView)findViewById(R.id.simpleGrid);
grid.setAdapter(new MyPicsAdapter(this,image,text));
// grid.setAdapter(new ImageAdapter(this,image));
grid.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(),text[position],Toast.LENGTH_LONG).show();
Intent a= new Intent(getApplicationContext(),FullImage.class);
a.putExtra("id",position);
startActivity(a);
}
});
}
}
You can pass only the image as follows,
grid.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(),text[position],Toast.LENGTH_LONG).show();
Intent a = new Intent(getApplicationContext(),FullImage.class);
a.putExtra("id", image[position]);
startActivity(a);
}
});
Inside onCreate of FullImage Activity get the image and display it in the ImageView,
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_image);
int image = getIntent().getExtras().getInt("id");
ImageView imageView = (ImageView) findViewById(R.id.fullimage);
imageView.setImageResource(image);
}

java.lang.NullPointerException: Android Studio

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

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