Getting error on My array Adapter class .The error is on Startavtivity line i dont know why it is its working on other pahes but it shows error on this page .So could you please help me out
ERROR" The Constructor Intent(MyArrayAdapter,Class<Add_new_employee >undefined)
package com.example.employeemanager;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
public class MyArrayAdapter extends ArrayAdapter<Student> {
Context context;
int layoutResourceId;
ArrayList<Student> students = new ArrayList<Student>();
public MyArrayAdapter(Context context, int layoutResourceId,ArrayList<Student> studs)
{
super(context, layoutResourceId, studs);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.students = studs;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View item = convertView;
StudentWrapper StudentWrapper = null;
if (item == null)
{
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
item = inflater.inflate(layoutResourceId, parent, false);
StudentWrapper = new StudentWrapper();
StudentWrapper.name = (TextView) item.findViewById(R.id.textName);
StudentWrapper.age = (TextView) item.findViewById(R.id.textAge);
StudentWrapper.address = (TextView) item.findViewById(R.id.textAddr);
StudentWrapper.edit = (Button) item.findViewById(R.id.btnEdit);
StudentWrapper.delete = (Button) item.findViewById(R.id.btnDelete);
StudentWrapper.checkBox = (CheckBox) item.findViewById(R.id.checkBox1);
item.setTag(StudentWrapper);
}
else
{
StudentWrapper = (StudentWrapper) item.getTag();
}
Student student = students.get(position);
StudentWrapper.name.setText(student.getName());
StudentWrapper.age.setText(student.getAge());
StudentWrapper.address.setText(student.getAddress());
StudentWrapper.edit.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
startActivity(new Intent
(MyArrayAdapter.this,Add_new_employee.class) );
}
});
StudentWrapper.delete.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
StudentWrapper.checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
Toast.makeText(context, "Checkox", Toast.LENGTH_LONG).show();
}
});
return item;
}
protected void startActivity(Intent intent) {
// TODO Auto-generated method stub
}
static class StudentWrapper
{
TextView name;
TextView age;
TextView address;
Button edit;
Button delete;
CheckBox checkBox;
}
}
Inseted of this
startActivity(new Intent
(MyArrayAdapter.this,Add_new_employee.class) );
use this
context.startActivity(new Intent
(context,Add_new_employee.class) );
Note: Make sure you had declared Add_new_employee in android manifest.xml
Try
startActivity(new Intent
(getBaseContext(),Add_new_employee.class) );
Related
I am making a practice app for my self creating friends profile my self in my app and having their avatar as imageview and name,nickname as text view it accepts object but it never shows anything on recyclerview
Please Help!
My main activity.java
package rex.MyFriends;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.OnItemTouchListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
public class MainActivity extends AppCompatActivity {
FloatingActionButton btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView view = findViewById(R.id.elementsview);
btn = (FloatingActionButton) findViewById(R.id.newfbtn);
view.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
view.setAdapter(new Friendsadapter(this));
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getBaseContext(),FriendsAdder.class));
}
});
}
}
my FriendAdder activity
package rex.MyFriends;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class FriendsAdder extends AppCompatActivity {
TextView name,nickname;
Button add ,selectimage;
ImageView image;
String imgpath;
private static final int SELECT_IMAGE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.friendsadder);
name = findViewById(R.id.name);
nickname = findViewById(R.id.nickname);
add = findViewById(R.id.add);
selectimage = findViewById(R.id.selimg);
image = findViewById(R.id.disimg);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(name.toString().isEmpty() || nickname.toString().isEmpty() || image.getDrawable()==null){
Toast.makeText(getBaseContext(),"please fill every thing!",Toast.LENGTH_SHORT).show();
}
else{
FriendList.addFriend(name.toString(),nickname.toString(),imgpath);
finish();
Toast.makeText(getBaseContext(),"Friend Added!",Toast.LENGTH_SHORT).show();
}
}
});
selectimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Your Friends Avatar!"), SELECT_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==SELECT_IMAGE && resultCode== Activity.RESULT_OK){
imgpath= data.getData().getPath();
Toast.makeText(getBaseContext(),imgpath,Toast.LENGTH_LONG).show();
image.setImageURI(data.getData());
}
}
}
my adapter class
package rex.MyFriends;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.io.File;
public class Friendsadapter extends RecyclerView.Adapter<Friendsadapter.FriendsHolder> {
Context context;
public Friendsadapter(Context context) {
this.context = context;
}
#NonNull
#Override
public FriendsHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.friendrow,null,false);
return new FriendsHolder(view);
}
#Override
public void onBindViewHolder(#NonNull FriendsHolder holder, int position) {
FriendList.Friend friend = (FriendList.Friend) FriendList.friendlist.get(position);
holder.nickname.setText(friend.nickname);
holder.name.setText(friend.name);
File imgFile = new File(friend.imgpath);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
holder.image.setImageBitmap(myBitmap);
}
}
#Override
public int getItemCount() {
return FriendList.friendlist.size();
}
public class FriendsHolder extends RecyclerView.ViewHolder {
TextView name,nickname;
ImageView image;
public FriendsHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.name);
nickname = itemView.findViewById(R.id.nickname);
image = itemView.findViewById(R.id.imageView2);
}
}
}
A helper Class I made with static Array list of Friend object acting as A runtime temporary database to add and remove Friend used in adapter class to display
package rex.MyFriends;
import java.util.ArrayList;
public class FriendList {
public static ArrayList<Friend> friendlist = new ArrayList<>();
public static class Friend {
String name;
String nickname;
String imgpath ;
public Friend(String name, String nickname, String imgpath) {
this.name = name;
this.nickname = nickname;
this.imgpath = imgpath;
}
}
public static void addFriend(String name, String nickname, String imgpath){
Friend friend = new Friend(name,nickname,imgpath);
friendlist.add(friend);
}
public int getSize(){
return friendlist.size();
}
public Friend getFriend(int position){
return friendlist.get(position);
}
}
Where the RecyclerView is handled adapterName.notifyDataSetChanged (); you need to run.
In your case, the data is collected statically. The place where the data is processed is a different Activity.
After switching to the new screen and adding data, you will need to update your adapter in onResume if you want the relevant data to appear when you come back. Recyclerview will appear blank since there is no data in its initial state.
#Override
public void onResume() {
super.onResume();
adapter.notifyDataSetChanged();
}
Hello friend i am new in android i want to know how to save ToggleButton state in custom ArrayAdapter i create custom ListView with help of ArrayAdapter now i want how save its state in Adapter here is my code pleae explain what logic used to achieve this goal i am on beginner level don't how to achieve this goal?
package bible.swordof.God;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.opengl.Visibility;
import android.preference.PreferenceManager;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;
import com.hitomi.cmlibrary.CircleMenu;
import com.hitomi.cmlibrary.OnMenuSelectedListener;
import com.hitomi.cmlibrary.OnMenuStatusChangeListener;
import java.util.List;
import java.util.Locale;
import es.dmoral.toasty.Toasty;
import static android.content.Context.MODE_PRIVATE;
import static android.database.sqlite.SQLiteDatabase.CONFLICT_NONE;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.V;
import static android.support.constraint.Constraints.TAG;
import static android.support.v4.content.ContextCompat.createDeviceProtectedStorageContext;
import static android.support.v4.content.ContextCompat.startActivity;
public class FullverseAdopter extends ArrayAdapter < String > {
private ALLVERSE activity;
private List < String > versenumber;
private List < String > verseid;
private List < String > verselist;
private List < String > refernce;
TextToSpeech textToSpeech;
private DatabaseHelper mDBHelper;
private SQLiteDatabase mDb;
private boolean save;
public static final String MyPREFERENCES = "MyPrefs";
//check for availabe language
int result;
public FullverseAdopter(ALLVERSE context, int resource, List < String > versenumber, List < String > verselist, List < String > refernce, List < String > verseid) {
super(context, resource, versenumber);
this.activity = context;
this.versenumber = versenumber;
this.verselist = verselist;
this.refernce = refernce;
this.verseid = verseid;
}
#Override
public int getCount() {
return versenumber.size();
}
#Override
public String getItem(int position) {
return versenumber.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.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.versedisplayrow, parent, false);
// get all UI view
holder = new ViewHolder(convertView);
// set tag for holder
holder.versenumber = (TextView) convertView.findViewById(R.id.versenumber);
holder.verselist = (TextView) convertView.findViewById(R.id.verse);
convertView.setTag(holder);
} else {
// if holder created, get tag from view
holder = (ViewHolder) convertView.getTag();
}
holder.versenumber.setText(versenumber.get(position));
holder.verselist.setText(verselist.get(position));
//share verse
holder.share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toasty.info(activity, "Sharing a verse.", Toast.LENGTH_SHORT, true).show();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, refernce.get(position) + ":" + versenumber.get(position) + '\n' + verselist.get(position));
sendIntent.setType("text/plain");
activity.startActivity(sendIntent);
}
});
textToSpeech = new TextToSpeech(activity, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
result = textToSpeech.setLanguage(Locale.ENGLISH);
} else {
Toast.makeText(activity, "YOUR DEVICE NOT SUPPORTED", Toast.LENGTH_SHORT).show();
}
}
});
//My toggle button
holder.bookmark.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
} else {
}
}
});
//mDBHelper = new DatabaseHelper(activity);
//mDb = mDBHelper.getWritableDatabase();
//ContentValues contentValues=new ContentValues();
//contentValues.put("id",verseid.get(position));
//contentValues.put("bookname",refernce.get(position));
//contentValues.put("versenumber",versenumber.get(position));
//contentValues.put("verse",verselist.get(position));
//long check=mDb.insert("favourite",null,contentValues);
//Log.d("MY_TAG","DB IS NOW "+check);
//Toasty.success(activity, "Added in favouite"+check, Toast.LENGTH_SHORT, true).show();
holder.speakverse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(activity, "I AM CLICKED", Toast.LENGTH_SHORT).show();
if (result == TextToSpeech.LANG_NOT_SUPPORTED || result == TextToSpeech.LANG_MISSING_DATA) {
Toast.makeText(activity, "Language not supported or Missing", Toast.LENGTH_SHORT).show();
} else {
textToSpeech.speak(verselist.get(position), TextToSpeech.QUEUE_FLUSH, null);
}
}
});
/* holder.removebookmark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getWritableDatabase();
// long delete= mDb.delete("favourite","id=?",new String[]{verseid.get(position)});
//Toasty.error(activity, "Remove in favouite"+delete, Toast.LENGTH_SHORT, true).show();
}
});*/
return convertView;
}
static class ViewHolder {
private ToggleButton favourite;
private TextView versenumber;
private TextView verselist;
private CircleMenu circleMenu;
private ImageView share;
//toggle button
public ToggleButton bookmark;
private boolean defaultvalue;
private ALLVERSE activity;
private ImageView speakverse;
public ViewHolder(View v) {
versenumber = (TextView) v.findViewById(R.id.versenumber);
verselist = (TextView) v.findViewById(R.id.verse);
share = (ImageView) v.findViewById(R.id.share);
bookmark = (ToggleButton) v.findViewById(R.id.adbookmark);
speakverse = (ImageView) v.findViewById(R.id.speakverse);
}
}
}
Ideally an adapter is an object to adapt a particular dataset to render a view within a listview. So you should have a data structure (class object) for every row visible in that list view and put it in an array list. Based on the position in getView method, retrieve the data for the row and initialize views from this data. Now this data set can be saved on server or in local memory in any format preferably in JSON and can be retrieved back in future.
I am making note taking app.i have two fragments in my app first fragment A (ListFragment) contains the recycler adapter .
while when I press adding floating button first fragment A (ListFragment) is replaced with next fragment B(AddingFragment) in which I type new data and then again press adding floating button on fragment B(AddingFragment) to add that new data in data set and then press backfloating button on my fragment B to move back to Fragment A(with recycler adapter) .
This new data item is added to data list every time but never becomes visible in recycler adapter in Fragment A.
package com.example.anonymous.note_taking_app;
import android.app.ActionBar;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class AddingFragment extends Fragment {
public AddingFragment()
{
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_adding, container, false);
return view;
}
#Override
public void onResume()
{
super.onResume();
FloatingActionButton floating = (FloatingActionButton) getActivity().findViewById(R.id.addingfloatingbutton);
floating.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Log.i("floating_button", "floating button 2 clicked");
EditText title = (EditText) getActivity().findViewById(R.id.firsttextview);
EditText detial = (EditText) getActivity().findViewById(R.id.secondtextview);
DatabaseHelper db = new DatabaseHelper(getActivity().getApplication());
boolean insert = db.insert(title.getText()+"",detial.getText()+"");
if(insert==true)
{
com.example.anonymous.note_taking_app.ListAdapter l = new com.example.anonymous.note_taking_app.ListAdapter();
ListFragment.it.add(new ListItem(title.getText()+"",detial.getText()+""));
l.notifyItemInserted(ListFragment.it.size()-1);//DataSetChanged();
l.notifyDataSetChanged();
for(int i=0;i<ListFragment.it.size();i++)
{
Log.i("List item"+i+"", ListFragment.it.get(i).getNoteTitle());
}
Log.i("insertion", "is added");
}
else
{
Log.i("insertion", "is not added");
}
}
});
FloatingActionButton floatings = (FloatingActionButton) getActivity().findViewById(R.id.addcancelfloatingbutton);
floatings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
final FragmentManager fragmentManager = getFragmentManager();
fragmentManager.popBackStackImmediate();
}
});
}
}
//
package com.example.anonymous.note_taking_app;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
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.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Fragment;
import java.util.ArrayList;
/**
* Created by Anonymous on 12/13/2017.
*/
public class ListAdapter extends RecyclerView.Adapter<ListAdapter.holderclas> implements EditDilogue.EditDilougeinterface
{
static ArrayList<ListItem> i;
Context context;
View view;
ImageButton share;
ImageButton edit;
static int lastposition;
android.app.FragmentManager fm;
public ListAdapter(ArrayList<ListItem> i,android.app.FragmentManager fm)
{
this.i=i;
this.fm=fm;
}
public ListAdapter()
{
}
#Override
public ListAdapter.holderclas onCreateViewHolder(ViewGroup parent, int viewType)
{
view= LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item,parent,false);
holderclas h = new holderclas(view);
share = (ImageButton) view.findViewById(R.id.share);
edit = (ImageButton) view.findViewById(R.id.edit);
return h;
}
#Override
public void onBindViewHolder(ListAdapter.holderclas holder, final int position)
{
final int y= position;
lastposition = position;
final ListItem it = i.get(position);
holder.title.setText(it.getNoteTitle());
holder.details.setText(it.getNoteDetail());
ImageButton b =(ImageButton) view.findViewById(R.id.delete);
b.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Log.i("size", i.size()+"");
i.remove(y);
notifyDataSetChanged();
}
});
share.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Log.i("share", "share");
}
});
edit.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Log.i("edit", i.size()+"edit");
EditDilogue ed = new EditDilogue();
Bundle args = new Bundle();
args.putString("title", it.getNoteTitle());
args.putString("detail", it.getNoteDetail());
ed.setArguments(args);
ed.setTargetFragment(new ListFragment(),1);
ed.show(fm,"fragment");
}
});
}
#Override
public int getItemCount()
{
return i.size();
}
#Override
public void deleteandadd(String titlestring, String detailstring)
{
String oldtitle = i.get(lastposition).getNoteTitle();
String olddetail = i.get(lastposition).getNoteDetail();
Log.i("string", titlestring);
Log.i("string", detailstring);
}
public class holderclas extends RecyclerView.ViewHolder
{
TextView title;
TextView details;
public holderclas(View itemView)
{
super(itemView);
title=(TextView) itemView.findViewById(R.id.title);
details=(TextView) itemView.findViewById(R.id.detail);
}
}
}
//
package com.example.anonymous.note_taking_app;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.LinearLayoutManager;
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.EditText;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import java.util.ArrayList;
/**
* Created by Anonymous on 12/13/2017.
*/
public class ListFragment extends Fragment implements EditDilogue.EditDilougeinterface
{
RecyclerView recyClerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
public static ArrayList<ListItem> it;
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState)
{
it = new ArrayList<>();
View view = inflater.inflate(R.layout.fragment_list, parent, false);
FloatingActionButton floating = (FloatingActionButton) view.findViewById(R.id.listfloatingbutton);
floating.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Fragment frg = new AddingFragment();
FragmentManager manager = getFragmentManager();
FragmentTransaction trans = manager.beginTransaction();
trans.replace(R.id.placeholder,frg);
trans.addToBackStack("addingfragment");
trans.commit();
AddingFragment()).addToBackStack("addingfragment").commit();
}
});
for(int i=0;i<5;i++)
{
ListItem t = new ListItem("Time Bank",
"Bank should contain atleast $2000 rupees then i will leave this matter") ;
it.add(t);
}
recyClerView=(RecyclerView) view.findViewById(R.id.recycle);
FragmentManager fm = getFragmentManager();
com.example.anonymous.note_taking_app.ListAdapter l = new com.example.anonymous.note_taking_app.ListAdapter(it,fm);
recyClerView.setAdapter(l);
layoutManager = new LinearLayoutManager(getActivity());
recyClerView.setLayoutManager(layoutManager);
return view;
}
#Override
public void onResume()
{
super.onResume();
if(adapter!=null)
{
adapter.notifyDataSetChanged();
adapter.notifyItemInserted(ListFragment.it.size()-1);
}
}
#Override
public void deleteandadd(String titlestring, String detailstring)
{
String oldtitle = com.example.anonymous.note_taking_app.ListAdapter.i.get(com.example.anonymous.note_taking_app.ListAdapter.lastposition).getNoteTitle();
String olddetail = com.example.anonymous.note_taking_app.ListAdapter.i.get(com.example.anonymous.note_taking_app.ListAdapter.lastposition).getNoteDetail();
Log.i("string", titlestring);
Log.i("string", detailstring);
}
}
I'm having an issue passing an array into a listview
I can pass an image to the second activty but when I
try to pass an array to the listview I get a lang.NullPointerException error
and the app crashes.
any helpful input would be great Thanks
here is the code
Main Activity
package com.example.androidlistview;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
public class MainActivity extends Activity {
ListView listView;
// Defined the text values to show in ListView
String[] values = new String[]{"Barack Obama","Donald Trump","Bill Clinton",
"Hillary Clinton","Joe Biden"};
// Defined the image ids to show in ListView
Integer[] images = {
R.drawable.image1,R.drawable.image2,R.drawable.image3,R.drawable.image4,
R.drawable.image5
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// create the custom view
CustomView adapter = new CustomView(MainActivity.this, values, images);
// Get ListView object from xml
listView = (ListView) findViewById(R.id.container);
//set adapter
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
if(position == 0){
Intent contact = new Intent(MainActivity.this, Details.class);
String[] details= new String[]{"Barack Obama","The White House","1-234-567-8900",
"Barack.Obama#whitehouse.com","note"};
Integer image = images[0];
contact.putExtra("image", image);
contact.putExtra("details", details);
startActivity(contact);
}
if(position == 1){
Intent contact = new Intent(MainActivity.this, Details.class);
String[] details= new String[] {"Donald Trump","Trump Tower","1-234-567-8901",
"Donald.Trump#whitehouse.com","note"};
Integer image = images[1];
contact.putExtra("image", image);
contact.putExtra("details", details);
startActivity(contact);
}
if(position == 2){
Intent contact = new Intent(MainActivity.this, Details.class);
String[] details = new String[] {"Bill Clinton","New York","1-234-567-8902",
"Bill.Clinton#whitehouse.com","note"};
Integer image = images[2];
contact.putExtra("image", image);
contact.putExtra("details", details);
startActivity(contact);
}
if(position == 3){
Intent contact = new Intent(MainActivity.this, Details.class);
String[] details = new String[] {"Hillary Clinton","New Jersey","1-234-567-8903",
"Hillary.Clinton#whitehouse.com","note"};
Integer image = images[3];
contact.putExtra("image", image);
contact.putExtra("details", details);
startActivity(contact);
}
if(position == 4){
Intent contact = new Intent(MainActivity.this, Details.class);
String[] details= new String[] {"Joe Biden","OHIO","1-234-567-8903",
"Joe.Biden#whitehouse.com","note"};
Integer image = images[4];
contact.putExtra("image", image);
contact.putExtra("details", details);
startActivity(contact);
}
}
});
}
}
Second Activity I want to pass the array to
package com.example.androidlistview;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Details extends Activity {
ListView list;
String []web={"Name:","Address:","Phone Number:","Email:","Note:"};
int image;
String[] details;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
// create the custom view
CustomList Adapter= new CustomList(Details.this, web, details);//, details should go here
// Get ListView object from xml
list=(ListView)findViewById(R.id.list);
//set adapter
list.setAdapter(Adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
}
});
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
image= bundle.getInt("image");
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setImageResource(image);
}
}
}
and the custom view i'm using for the Second Activity details
package com.example.androidlistview;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class CustomList extends ArrayAdapter<String>{
private final Activity mContext;
private final String[] web;
private final String[] details;
public CustomList(Activity mContext,String[] web, String[] details){ //, String[] details should go here
super(mContext, R.layout.list_single, web);
this.mContext=mContext;
this.web=web;
this.details=details;
}
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = mContext.getLayoutInflater();
View rowView= inflater.inflate(R.layout.list_single, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
txtTitle.setText(web[position]);
TextView txtTitle1 = (TextView)rowView.findViewById(R.id.txt1);
txtTitle1.setText(details[position]);
return rowView;
}
}
This is what i did to fix this
Main Activity
package com.example.androidcontacts;
import android.app.ListActivity;
import android.content.CursorLoader;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.CursorAdapter;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleCursorAdapter;
public class MainActivity extends ListActivity {
ListView mylist;
SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Uri allContacts = Uri.parse("content://"+"com.example.androidcontacts.Books" + "/Contact");
Cursor c;
CursorLoader cursorLoader = new CursorLoader(
this,allContacts,null,null,null,null);
c = cursorLoader.loadInBackground();
String[] columns = new String[] {Contact._ID,Contact.TITLE,Contact.AUTHOR,Contact.YEAR,Contact.IMAGE};
int[] views = new int[] {R.id.contactID,R.id.contactName,R.id.contactAuthor,R.id.contactYear,R.id.Image};
SimpleCursorAdapter adapter;
adapter = new SimpleCursorAdapter(this, R.layout.activity_main,
c, columns, views,CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
this.setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView list, View view, int position, long id) {
//Intent i=new Intent(MainActivity.this,Details.class);
//startActivity(i);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
if(id == R.id.action_search){
Intent intent = new Intent(this, Search.class);
startActivity(intent);
finish();
return true;
}
if(id == R.id.action_add){
Intent intent = new Intent(this, Add.class);
startActivity(intent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Second activity Details
package com.example.androidlistview;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class Details extends Activity {
//Variables for Bundle
int image;
String name;
String address;
String phone;
String email;
String note;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
Button SMS = (Button) findViewById(R.id.button1);
SMS.setOnClickListener(new OnClickListener() {
//when button1 is clicked open messenger
#Override
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", phone, null)));
}
});
Button Email = (Button) findViewById(R.id.button2);
Email.setOnClickListener(new OnClickListener() {
//when button2 is clicked open email
#Override
public void onClick(View v) {
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:"));
emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { email });
startActivity(Intent.createChooser(emailIntent, "Choose Email Client"));
}
});
Button Phone = (Button) findViewById(R.id.button3);
Phone.setOnClickListener(new OnClickListener() {
//when button3 is clicked start call
#Override
public void onClick(View v) {
startActivity(new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", phone, null)));
}
});
// get details passed from MainActivity
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
image= bundle.getInt("image");
ImageView imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setImageResource(image);
name = bundle.getString("name");
TextView nameView = (TextView) findViewById(R.id.name1);
nameView.setText(name);
address = bundle.getString("address");
TextView addressView = (TextView) findViewById(R.id.address1);
addressView.setText(address);
phone = bundle.getString("phone");
TextView phoneView = (TextView) findViewById(R.id.phone1);
phoneView.setText(phone);
email = bundle.getString("email");
TextView emailView = (TextView) findViewById(R.id.email1);
emailView.setText(email);
note = bundle.getString("note");
TextView noteView = (TextView) findViewById(R.id.note1);
noteView.setText(note);
}
}
}
My Custom View
package com.example.androidlistview;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomView extends ArrayAdapter<String>{
private final Activity context;
private final String[] values;
private final Integer[] images;
//Constructor
public CustomView(Activity context,String[] values, Integer[] images) {
super(context, R.layout.single_row, values);
this.context = context;
this.values = values;
this.images = images;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.single_row, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
txtTitle.setText(values[position]);
ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
imageView.setImageResource(images[position]);
return rowView;
}
}
I am trying to populate an arraylist with three variable. After that the arraylist should display its content in a listview. when i run this class logcat shows an error which is completely unknown to me. Following is the class I am using.
import java.util.ArrayList;
import android.app.Activity;
import android.app.ActionBar.LayoutParams;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Secondscreen extends Activity {
String pName ;
int pPrice;
String pDisc;
int total;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondscreen);
ListView lv= (ListView) findViewById(R.id.listView1);
//TextView showCartContent = (TextView) findViewById(R.id.showCart);
final Button thirdBtn = (Button) findViewById(R.id.third);
//final LinearLayout lb = (LinearLayout) findViewById(R.id.secondLinear);
final Controller aController = (Controller) getApplicationContext();
final int cartSize = aController.getCart().getCartSize();
final ArrayList<Listitem> arrayList=new ArrayList<Listitem>();
BaseAdapter adapter= new BaseAdapter(){
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrayList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
LayoutInflater inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
#Override
public View getView(int position, View view, ViewGroup viewgroup) {
if (view == null) {
view=inflater.inflate(R.layout.pattern, null);
}
TextView tv=(TextView) view.findViewById(R.id.nameview);
TextView tv2=(TextView) view.findViewById(R.id.pdesc);
TextView tv3=(TextView) view.findViewById(R.id.priceView);
tv.setText(pName);
tv2.setText(pPrice);
tv3.setText(pDisc);
return view;
}
};
lv.setAdapter(adapter);
if(cartSize >0)
{
for(int i=0;i<cartSize;i++)
{
pName = aController.getCart().getProducts(i).getProductName();
pPrice = aController.getCart().getProducts(i).getProductPrice();
pDisc = aController.getCart().getProducts(i).getProductDesc();
Listitem item=new Listitem(pName, pPrice,pDisc);
arrayList.add(item);
adapter.notifyDataSetChanged();
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
Please Help me to solve this.
tv2.setText(pPrice);
pPrice is a int. setText(int) looks for a String id inside the R classes throwing a ResourceNotFoundException if the look-up fails. A quick fix is
tv2.setText(""+pPrice);
This way you are providing a String object to setText
Edit:
Change your getView this way:
#Override
public View getView(int position, View view, ViewGroup viewgroup) {
if (view == null) {
view=inflater.inflate(R.layout.pattern, null);
}
Listitem item = (Listitem)getItem(position)
TextView tv=(TextView) view.findViewById(R.id.nameview);
TextView tv2=(TextView) view.findViewById(R.id.pdesc);
TextView tv3=(TextView) view.findViewById(R.id.priceView);
tv.setText(item. pName);
tv2.setText(""+item.pPrice);
tv3.setText(item.pDisc);
return view;
}
You never get your objects from the ArrayList. Add this code to your getView() method:
ListItem item = arrayList.get(position);
tv.setText(item.pName);
tv2.setText(item.pPrice);
tv3.setText(item.pDisc);