I have a listview activity that displays an array (ml_main) from my custom class (ml_lists) and adapter (ml_my_adapter). The array is added to via another activity. I have a 3rd activity that I want to display the item and subitem in textviews when the appropriate listitem is selected. Its this last part that I am struggling with, my intent opens the 3rd activity but the textviews are empty (dont even appear), any help really appreciated, code below...
package com.example.adam.mylists;
public class ml_lists {
// Store the name of the item
private String mItem;
// Store the name of the subitem
private String mSubItem;
// Constructor that is used to create an instance of the list_my_list object
public ml_lists(String mItem, String mSubItem) {
this.mItem = mItem;
this.mSubItem = mSubItem;
}
public String getmItem() {
return mItem;
}
public void setmItem(String mItem) {
this.mItem = mItem;
}
public String getmSubItem() {
return mSubItem;
}
public void setmSubItem(String mSubItem) {
this.mSubItem = mSubItem;
}
}
package com.example.adam.mylists;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
/*The code is now stable to generate a list which is predefined, now need to amend so that
it is populated via user input*/
public class ml_main extends AppCompatActivity {
String item;
String subitem;
ArrayList<ml_lists> userlist = new ArrayList<>();
private ListView listView;
private ml_my_adapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ml_main);
final Context context = getApplicationContext();
final FloatingActionButton addnewitem = (FloatingActionButton) findViewById(R.id.floatingActionButton);
listView = findViewById(R.id.listview_list);
userlist.add(new ml_lists("Item 1 example", "Sub item 1 example"));
mAdapter = new ml_my_adapter(this, userlist);
listView.setAdapter(mAdapter);
addnewitem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent launchactivity = new Intent(context, ml_create_new_item_screen.class);
startActivityForResult(launchactivity, 1);
overridePendingTransition(R.anim.slide_in_up, R.anim.slide_out_up);
}
});
/*BELOW CODE TO SELECT ITEM FROM LISTVIEW AND OPEN IT BACK UP IN THE CREATE ITEM ACT*/
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
/*intent used to open selected activity into editor*/
Intent edititem = new Intent(context, ml_edit_existing_item_screen.class);
edititem.putExtra("item",item);
edititem.putExtra("subitem",subitem);
startActivity(edititem);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == Activity.RESULT_OK) {
item = data.getStringExtra("tempitem");
subitem = data.getStringExtra("tempsubitem");
userlist.add(new ml_lists(item, subitem));
mAdapter.notifyDataSetChanged();
}
if (resultCode == Activity.RESULT_CANCELED) {
Toast replacewithcode = Toast.makeText(ml_main.this, "replace with code", Toast.LENGTH_SHORT);
replacewithcode.show();
}
}
}
}
package com.example.adam.mylists;
import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/*Created by Adam Garnham*/
public class ml_my_adapter extends ArrayAdapter<ml_lists> {
private Context mContext;
private List<ml_lists> mList = new ArrayList<>();
public ml_my_adapter(#NonNull Context context, #LayoutRes ArrayList<ml_lists> list) {
super(context, 0, list);
mContext = context;
mList = list;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View listItem = convertView;
if (listItem == null)
listItem = LayoutInflater.from(mContext).inflate(R.layout.list_item, parent, false);
ml_lists currentItem = mList.get(position);
TextView mItem = (TextView) listItem.findViewById(R.id.textView_item);
mItem.setText(currentItem.getmItem());
TextView mSubItem = (TextView) listItem.findViewById(R.id.textView_subitem);
mSubItem.setText(currentItem.getmSubItem());
return listItem;
}
}
package com.example.adam.mylists;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
/**
* Created by Adam on 02/01/2018.
*/
public class ml_edit_existing_item_screen extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_existing_item_screen);
Intent edititem = getIntent();
String item = edititem.getStringExtra("item");
String subitem = edititem.getStringExtra("subitem");
TextView itemtextview = findViewById(R.id.itemtextview);
TextView subitemtextview = findViewById(R.id.subitemtextview);
itemtextview.setText(item);
subitemtextview.setText(subitem);
}
}
The problem with your code is that you are not assigning values to "item" and "subitem" in your on click listener. They are empty. You can fetch the values of current selected item by passing the selected position to userlist.
Most probably you can do something likes this.
ml_lists selectedItem=userlist.get(i);
item=selectedItem.getmItem();
subItem=selectedItem.getmSubItem();
Related
I am getting this error when doing intent. I don't know why it is coming. I need to go to the fragment to activity. I need to go to the next activity with the api in this application. I have tried many times and I am not getting the answer.**Cannot resolve method 'putExtra(java.lang.String, <lambda parameter>)'**I have given the image below How to do fragment to activity intent i am new android devloper
package com.kannada.newspaper.india.utils;
import static com.kannada.newspaper.india.Constant.EXTRA_OBJC;
import static com.kannada.newspaper.india.Constant.getApiUrl;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import com.kannada.newspaper.india.AppConfig;
import com.kannada.newspaper.india.Constant;
import com.kannada.newspaper.india.MainActivity;
import com.kannada.newspaper.india.R;
import com.kannada.newspaper.india.activities.ActivityCategoryDetail;
import com.kannada.newspaper.india.adapters.GalleryAdapter;
import com.kannada.newspaper.india.model.Category;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class FragmentCategory extends Fragment {
private Call<CallbackHome> callbackCall = null;
SharedPref sharedPref;
private View root_view;
public static final String EXTRA_OBJC = "key.EXTRA_OBJC";
private GalleryAdapter adapterCategory;
private GridView gridView;
private List<Category> mensWears;
private GalleryAdapter adapter;
private Category category;
public FragmentCategory() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,
Bundle savedInstanceState) {
requestAction();
category = (Category) getActivity().getIntent().getSerializableExtra(Constant.EXTRA_OBJC);
// Inflate the layout for this fragment
root_view = inflater.inflate(R.layout.fragment_phones,container,false);
((TextView) root_view.findViewById(R.id.txt_title_category)).setText(getResources().getString(R.string.home_title_category));
return root_view;
}
private void requestAction() {
new Handler().postDelayed(this::requestHomeData, Constant.DELAY_TIME);
}
private void requestHomeData() {
this.callbackCall = RestAdapter.createAPI(getApiUrl).getHome(AppConfig.REST_API_KEY);
this.callbackCall.enqueue(new Callback<CallbackHome>() {
public void onResponse(Call<CallbackHome> call, Response<CallbackHome> response) {
CallbackHome responseHome = response.body();
if (responseHome == null || !responseHome.status.equals("ok")) {
return;
}
displayData(responseHome);
}
public void onFailure(Call<CallbackHome> call, Throwable th) {
Log.e("onFailure", th.getMessage());
if (!call.isCanceled()) {
}
}
});
}
private void displayData(CallbackHome responseHome) {
displayCategory(responseHome.category);
}
private void displayCategory(List<Category> list) {
GridView gridView = (GridView) root_view.findViewById(R.id.gridHolder);
adapterCategory = new GalleryAdapter(getActivity(), list);
gridView.setAdapter(adapterCategory);
GalleryAdapter.setOnItemClickListener((v, obj, position) -> {
Intent intent = new Intent(getActivity(), ActivityCategoryDetail.class);
intent.putExtra(EXTRA_OBJC, obj);
startActivity(intent);
});
LinearLayout lyt_category = root_view.findViewById(R.id.lyt_category);
if (list.size() > 0) {
// lyt_category.setVisibility(View.VISIBLE);
} else {
// lyt_category.setVisibility(View.GONE);
}
}
}
GalleryAdapter adapter
public class GalleryAdapter extends BaseAdapter {
private Context context;
private List<Category> mensWears;
public GalleryAdapter(Context context, List<Category> mensWears) {
this.context = context;
this.mensWears = mensWears;
}
public static void setOnItemClickListener(Object o) {
}
#Override
public int getCount() {
return mensWears.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i,View view,ViewGroup viewGroup) {
final Category mensWear = mensWears.get(i);
if (view == null) {
final LayoutInflater layoutInflater = LayoutInflater.from(context);
view = layoutInflater.inflate(R.layout.custom_gallery_layout, null);
}
//For text
TextView prdId = view.findViewById(R.id.category_name);
ImageView imageView = view.findViewById(R.id.category_image);
// prdId.setText(prdId.toString());
Picasso.get()
.load(getApiUrl + "/upload/category/" + mensWears.get(i).category_image())
.placeholder(R.drawable.ic_thumbnail)
.into(imageView);
prdId.setText(mensWears.get(i).getItemName());
// //For images
// final ImageView imageView = view.findViewById(R.id.name);
// if(!TextUtils.isEmpty(mensWear.getItemName())){
//
//// Picasso.with(context).load(imageUrlFromServer+mensWear.category_image())
//// .into(imageView);
return view;
}
}
You cannot put Object type in putExtra , it has to be either serailized, string, double and other primitive type.
You can do like this:
Category category = (Category)adapter.getItemAtPosition(pos);
or this should also work:
Category category = (Category) obj
then,
intent.putExtra(EXTRA_OBJC,category)
Note: Your Category class should implement parcelable or serilizable to be passed as an intent.
public class Category implements Serializable {
..........}
I am making a flash card app with SwipeCard
This is my FlashCardActivity:
import android.os.Bundle;
import android.text.style.TtsSpan;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import com.google.gson.Gson;
import com.lorentzos.flingswipe.SwipeFlingAdapterView;
import org.koreanlab.fabloading.R;
import org.koreanlab.fabloading.adapter.CardListAdapter;
import org.koreanlab.fabloading.basickit.BasicCompatActivity;
import org.koreanlab.fabloading.basickit.remote.RemoteService;
import org.koreanlab.fabloading.basickit.remote.ServiceGenerator;
import org.koreanlab.fabloading.item.CardItem;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class FlashCardActivity extends BasicCompatActivity {
private String TAG = getClass().getSimpleName();
private ArrayList<CardItem> cardList;
private ArrayAdapter<String> cardAdapter;
private CardListAdapter cardListAdapter;
private int i;
CardItem newCard;
#BindView(R.id.frame)
SwipeFlingAdapterView flingContainer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flashcard);
ButterKnife.bind(this);
cardList = new ArrayList<>();
Log.d(TAG, "cardList created");
// get Two Words;
cardList.add(getCardItem());
cardList.add(getCardItem());
Log.d(TAG, "added Card");
cardListAdapter = new CardListAdapter(this, R.layout.card_item, cardList);
Log.d(TAG, "adapter created: " + (cardListAdapter == null ? "cardAdapter is NULL" : "cardAdapter is not NULL"));
flingContainer.setAdapter(cardListAdapter);
Log.d(TAG, "adapter set: " + (flingContainer == null ? "flingContainer is NULL" : "flingContainer is not NULL"));
flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
#Override
public void removeFirstObjectInAdapter() {
// this is the simplest way to delete an object from the Adapter (/AdapterView)
Log.d("LIST", "removed object!");
cardList.remove(0);
cardListAdapter.notifyDataSetChanged();
}
#Override
public void onLeftCardExit(Object dataObject) {
//Do something on the left!
//You also have access to the original object.
//If you want to use it just cast it (String) dataObject
makeToast(FlashCardActivity.this, "Left!");
}
#Override
public void onRightCardExit(Object dataObject) {
makeToast(FlashCardActivity.this, "Right!");
}
#Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
// Ask for more data here
Log.d(TAG, "onAdapterAboutToEmpty: "+itemsInAdapter);
cardList.add(getCardItem());
cardListAdapter.notifyDataSetChanged();
Log.d("LIST", "notified");
i++;
}
#Override
public void onScroll(float scrollProgressPercent) {
View view = flingContainer.getSelectedView();
view.findViewById(R.id.item_swipe_right_indicator).setAlpha(scrollProgressPercent < 0 ? -scrollProgressPercent : 0);
view.findViewById(R.id.item_swipe_left_indicator).setAlpha(scrollProgressPercent > 0 ? scrollProgressPercent : 0);
}
});
// Optionally add an OnItemClickListener
flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
#Override
public void onItemClicked(int itemPosition, Object dataObject) {
makeToast(FlashCardActivity.this, "Clicked!");
}
});
}
#OnClick(R.id.right)
public void right() {
/**
* Trigger the right event manually.
*/
flingContainer.getTopCardListener().selectRight();
}
#OnClick(R.id.left)
public void left() {
flingContainer.getTopCardListener().selectLeft();
}
public CardItem getCardItem() {
// No problem here.
return newCard;
}
}
Notice that, getCardItem() just get one card. First of all, it calls two cards and the cardList has two cards when activity has created. And after that I'd like to get just one card after swipe. getCardItem() has no problem. I can see that I receives the data from my Server.
This is my custom CardListAdapter:
import android.content.Context;
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.ArrayAdapter;
import android.widget.TextView;
import org.koreanlab.fabloading.R;
import org.koreanlab.fabloading.item.CardItem;
import java.util.ArrayList;
import java.util.List;
public class CardListAdapter extends ArrayAdapter {
private final String TAG = this.getClass().getSimpleName();
private Context context;
private int cardResId;
private int frontResId;
private int backResId;
private List<CardItem> cardList;
private LayoutInflater mInflater;
//this, R.layout.card_item, R.id.card_front, R.id.card_back, cardList
public CardListAdapter(Context context, int cardResId, ArrayList<CardItem> cardList) {
super(context, cardResId);
this.context = context;
this.cardResId = cardResId;
this.cardList = cardList;
mInflater = LayoutInflater.from(context);
}
public void setItem(CardItem newItem) {
Log.d(TAG, "setItem");
for (int i = 0; i < cardList.size(); i++) {
CardItem item = cardList.get(i);
if (item.seq == newItem.seq) {
cardList.set(i, newItem);
break;
}
}
}
#Override
public int getCount() {
Log.d(TAG, "getVIew");
return 0;
}
public int getPosition(CardItem item) {
Log.d(TAG, "getPosition = "+item);
return cardList.indexOf(item);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
convertView = mInflater.inflate(cardResId, parent,false);
holder = new ViewHolder();
Log.d(TAG, "getView");
holder.frontTV = convertView.findViewById(R.id.card_front);
holder.backTV = convertView.findViewById(R.id.card_back);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.frontTV.setText((String)getItem(position));
holder.backTV.setText((String)getItem(position));
return convertView;
}
static class ViewHolder
{
TextView frontTV, backTV;
}
}
I checked many blogs and other Q&A, but I haven't figured it out how to solve this problem. That activity keeps going back after receiving 'one word' data from the Server and It doesn't show any error messages.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am trying to write a ListView with custom Adapter in android.when my code is done i got 'java.lang.NullPointerException' .
I checked again and again but can not fix this error.
this is MainActivity code:
package com.example.sayres.myapplication3_listview;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity{
private EditText mainActivity_editText_userName, mainActivity_editText_password;
private Button mainActivity_btn_login, mainActivity_btn_exit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
mainActivity_editText_userName = (EditText) findViewById(R.id.mainActivity_editText_userName);
mainActivity_editText_password = (EditText) findViewById(R.id.mainActivity_editText_password);
mainActivity_btn_login = (Button) findViewById(R.id.mainActivity_btn_login);
mainActivity_btn_exit = (Button) findViewById(R.id.mainActivity_btn_exit);
mainActivity_btn_exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
mainActivity_btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginprocess();
}
});
}
private void loginprocess() {
String userName = mainActivity_editText_userName.getText().toString();
String password = mainActivity_editText_password.getText().toString();
Log.i("====>", "UserName= "+ userName+" Passwotd: "+ password);
Toast.makeText(getApplicationContext(),userName, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
startActivity(intent);
}
}
in MainActivity code i create intent for go to HomeActivity.
HomeActivity code:
package com.example.sayres.myapplication3_listview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import com.example.sayres.myapplication3_listview.adapter.ContactAdapter;
import com.example.sayres.myapplication3_listview.model.Contact;
import java.util.List;
public class HomeActivity extends AppCompatActivity {
private ListView listViewHome;
private List<Contact> contacts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
initViews();
}
private void initViews() {
listViewHome = (ListView) findViewById(R.id.listViewHome);
for (int i = 0; i < 1000; i++) {
int pic = 0;
if (i % 2 == 0) {
pic = R.drawable.man;
} else {
pic = R.drawable.female;
}
contacts.add(createContact("name " + i, "family " + i, "5526576", pic));
}
ContactAdapter adapter = new ContactAdapter(this, R.layout.row_contacts_list, contacts);
listViewHome.setAdapter(adapter);
}
private Contact createContact(String name, String family, String number, int picture) {
return new Contact(name, family, number, picture);
}
}
I got Error In this line: contacts.add(createContact("name " + i, "family " + i, "5526576", pic));
this error
at com.example.sayres.myapplication3_listview.HomeActivity.initViews(HomeActivity.java:34)
at com.example.sayres.myapplication3_listview.HomeActivity.onCreate(HomeActivity.java:21)
this is ContactAdapter extends ArrayAdapter code:
package com.example.sayres.myapplication3_listview.adapter;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.example.sayres.myapplication3_listview.R;
import com.example.sayres.myapplication3_listview.model.Contact;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
public class ContactAdapter extends ArrayAdapter<Contact> {
private Context context;
private int layout;
private List<Contact> contacts;
public ContactAdapter(Context context, int layout, List<Contact> contacts) {
super(context, layout, contacts);
this.context = context;
this.layout = layout;
this.contacts = contacts;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rootView = inflater.inflate(layout, null);
if (position % 2 == 0 ){
rootView.setBackgroundColor(Color.parseColor("#12ffff"));
}else {
rootView.setBackgroundColor(Color.parseColor("#FFFF12"));
}
/**
* set reference from row_contacts_list.xml
*/
TextView contactList_name = (TextView) rootView.findViewById(R.id.contactList_name);
TextView contactList_family = (TextView) rootView.findViewById(R.id.contactList_family);
CircleImageView profile_picture = (CircleImageView) rootView.findViewById(R.id.profile_picture);
contactList_name.setText(contacts.get(position).getContactName());
contactList_family.setText(contacts.get(position).getContactFamily());
profile_picture.setImageResource(contacts.get(position).getContactPicture());
return rootView;
}
}
my Contact class is a simple class with setter and getter:
package com.example.sayres.myapplication3_listview.model;
public class Contact {
private String contactName,contactFamily, contactNumber;
private int contactPicture;
public Contact() {
}
public Contact(String contactName, String contactFamily, String contactNumber, int contactPicture) {
this.contactName = contactName;
this.contactFamily = contactFamily;
this.contactNumber = contactNumber;
this.contactPicture = contactPicture;
}
where is my mistake?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// Init the contacts
contacts = new ArrayList<Contact>();
initViews();
}
I have an app that currently displays a list of names in a ListView. Each item in the ListView consists of a CheckBox and an EditText.
The list of names is provided by an ArrayList of 'Prospects' objects
When the user selects the CheckBox I want to return the state of this check box and assign it the Propsects object at the relevant position in the ArrayList so it can be saved for use the next time the app is opened (this will be done using CSV).
I'm struggling with the correct listener to use to do this as this is my first attempt at Android programming. I've been unable to find any examples that match what i'm trying to achieve or if I have i've not understood them!.
Any help would be appreciated!
My code is as follows:
package com.veetox.networkmarketingmanager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.veetox.networkmarketingmanager.data.Prospects;
import com.veetox.networkmarketingmanager.helper.FileHelper;
import com.veetox.networkmarketingmanager.helper.ProspectListAdapter;
import com.veetox.networkmarketingmanager.helper.ProspectViewHolder;
import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity
{
public static ArrayList<Prospects> prospectList = new ArrayList<>();
Resources res;
FileHelper fileHelper = new FileHelper(this);
ListView prospectsListEntry;
CheckBox prospectsCheckBox;
EditText prospectsEditText;
ProspectListAdapter pla;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prospectsCheckBox = (CheckBox) findViewById(R.id.pr_checkBox);
prospectsEditText = (EditText) findViewById(R.id.pr_name);
res = getResources();
createProspectList();
prospectsListEntry.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View item, int position, long id)
{
//Create new Prospect cloning Prospect at row in ItemList that was clicked
Prospects prospect = pla.getItem(position);
//Change the state of contacted from true to false or vice versa
prospect.toggleContacted();
//Create a ProspectViewHolder to hold the view for the row clicked
ProspectViewHolder viewHolder = (ProspectViewHolder) item.getTag();
viewHolder.getCheckBox().setChecked(prospect.isChecked());
prospectList.get(position) ;
pla.notifyDataSetChanged();
}
});
}
public void testProspects(View view)
{
prospectList = fileHelper.testProspects();
pla.notifyDataSetChanged();
}
public void createProspectList()
{
fileHelper = new FileHelper(this);
//Comment before testing
//prospectList = fileHelper.loadProspects();
//Uncomment for testing
prospectList = fileHelper.testProspects();
//Create the list
pla = new ProspectListAdapter(this, R.layout.prospects_list_layout, prospectList);
prospectsListEntry = (ListView) findViewById(R.id.prospects_list);
prospectsListEntry.setAdapter(pla);
}
}
package com.veetox.networkmarketingmanager.helper;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import com.veetox.networkmarketingmanager.MainActivity;
import com.veetox.networkmarketingmanager.R;
import com.veetox.networkmarketingmanager.data.Prospects;
import java.util.ArrayList;
/**
* Created by Matt on 29/09/2016.
*/
public class ProspectListAdapter extends ArrayAdapter<Prospects>
{
private Context context;
private int layoutResourceId;
private ArrayList<Prospects> prospect;
public ProspectListAdapter(Context context, int layoutResourceId, ArrayList<Prospects> prospect)
{
super(context, layoutResourceId, prospect);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.prospect = prospect;
}
public int getCount()
{
return prospect.size();
}
public Prospects getItem(int position)
{
return prospect.get(position);
}
public long getItemId(int position)
{
return position;
}
#Override
#NonNull
public View getView(int position, View convertView, #NonNull ViewGroup parent)
{
View v = convertView;
if (v == null)
{
LayoutInflater vi;
vi = LayoutInflater.from(context);
v = vi.inflate(layoutResourceId, parent, false);
}
Prospects prospects = prospect.get(position);
if (prospects != null)
{
TextView prname = (TextView) v.findViewById(R.id.pr_name);
CheckBox complete = (CheckBox) v.findViewById(R.id.pr_checkBox);
if (prname != null)
{
prname.setText(prospects.getName());
}
if (complete != null)
{
complete.setChecked(prospects.isChecked());
}
}
return v;
}
}
package com.veetox.networkmarketingmanager.data;
/**
* A Prospective customer
*/
public class Prospects
{
private String prospectname;
private boolean contacted;
private String stringContacted;
public Prospects(String aName, boolean contacted)
{
prospectname = aName;
this.contacted = contacted;
}
public Prospects(String aName, String contacted)
{
prospectname = aName;
this.stringContacted = contacted;
}
public Prospects(String aName)
{
prospectname = aName;
}
public String getName()
{
return prospectname;
}
public boolean isChecked()
{
return contacted;
}
public void setName (String aName)
{
prospectname = aName;
}
public void setContacted(boolean contacted)
{
this.contacted = contacted;
}
public void toggleContacted()
{
if (contacted)
{
contacted = false;
}
else
{
contacted = true;
}
}
}
package com.veetox.networkmarketingmanager.helper;
import android.content.Context;
import android.widget.Toast;
import com.veetox.networkmarketingmanager.data.Prospects;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Map;
import java.util.Scanner;
/**
* Created by Matt on 28/09/2016.
*/
public final class FileHelper
{
Context context;
public FileHelper(Context aContext)
{
context = aContext;
}
public void saveProspects(ArrayList<Prospects> prospects)
{
ArrayList<Prospects> p = prospects;
BufferedWriter bufferedFileWriter = null;
try
{
File aFile = new File(context.getFilesDir(), "prospects.csv");
aFile.createNewFile();
bufferedFileWriter = new BufferedWriter(new FileWriter(aFile));
for (Prospects eachProspect : p)
{
bufferedFileWriter.write(eachProspect.getName());
bufferedFileWriter.write(",");
bufferedFileWriter.write(String.valueOf(eachProspect.isChecked()));
bufferedFileWriter.newLine();
}
}
catch (Exception e)
{
e.printStackTrace();
// Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
}
finally
{
try
{
bufferedFileWriter.close();
}
catch (Exception e)
{
e.printStackTrace();
//Toast.makeText(context, e.toString(), Toast.LENGTH_SHORT).show();
}
}
}
public ArrayList<Prospects> loadProspects()
{
ArrayList<Prospects> prospectsList = new ArrayList<>();
Scanner bufferedScanner = null;
Scanner lineScanner = null;
try
{
File aFile = new File(context.getFilesDir(), "prospects.csv");
bufferedScanner = new Scanner(new BufferedReader(new FileReader(aFile)));
while (bufferedScanner.hasNextLine())
{
lineScanner = new Scanner(bufferedScanner.nextLine());
lineScanner.useDelimiter(",");
String prospect = lineScanner.next();
String contacted = lineScanner.next();
Prospects aProspect = new Prospects(prospect, contacted);
prospectsList.add(aProspect);
}
}
catch (Exception e)
{
e.printStackTrace();
//Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
}
finally
{
try
{
bufferedScanner.close();
}
catch (Exception e)
{
e.printStackTrace();
//Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
}
}
return prospectsList;
}
public ArrayList<Prospects> testProspects()
{
ArrayList<Prospects> p = new ArrayList<>();
Prospects q = new Prospects("Matt Lee", true);
Prospects r = new Prospects("Rosemary Watson", false);
Prospects s = new Prospects("Joe Bloggs", false);
Prospects t = new Prospects("Ronny Corbit", false);
Prospects u = new Prospects("Mr Man", false);
Prospects v = new Prospects("Mr Bond", true);
Prospects w = new Prospects("Mr Blobby", true);
Prospects x = new Prospects("Mary Rose", false);
Prospects y = new Prospects("Jane Doe", false);
Prospects z = new Prospects("Lucy Sanders", false);
p.add(q);
p.add(r);
p.add(s);
p.add(t);
p.add(u);
p.add(v);
p.add(w);
p.add(x);
p.add(y);
p.add(z);
return p;
}
}
You need to move your checkbox check(checked/notChecked) in adapter. you'll need ItemId to access and retrive the clicked item in ListView.
I want to display my values into tab layout when clicking one item in the list. My problem is how can I pass the value into one of my tab activity(TabActivity1) to appear in the first tab in my Tablayout while it displays the tablayout.xml, because whenever I clicked an item in the list it goes to my tablayout.xml which is correct but it doesnt have any value in it. Any help would be much appreciated.
heres my code:
Main.java
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class Main extends Activity {
public final static String TAG_RECIPE="com.example.getlistfromdb.RECIPE_NAME";
public final static String TAG_INGRIDIENTS="com.example.getlistfromdb.INGRIDIENTS";
private recipelistHelper dbrecipelistHelper = null;
private Cursor ourCursor = null;
private recipeAdapter adapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
try
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView myListView = (ListView) findViewById(R.id.myListView);
dbrecipelistHelper = new recipelistHelper(this);
dbrecipelistHelper.createDatabase();
dbrecipelistHelper.openDatabase();
ourCursor=dbrecipelistHelper.getCursor();
startManagingCursor(ourCursor);
adapter = new recipeAdapter(ourCursor);
myListView.setAdapter(adapter);
myListView.setOnItemClickListener(onListClick);
}
catch (Exception e)
{
Log.e("ERROR", "ERROR IN CODE: " + e.toString());
e.printStackTrace();
}
}
private AdapterView.OnItemClickListener onListClick = new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Cursor selectedCursor=(Cursor)adapter.getItem(position);
selectedCursor.moveToPosition(position);
String ingridients = dbrecipelistHelper.getCursor(selectedCursor);
String name = selectedCursor.getString(
selectedCursor.getColumnIndexOrThrow("Recipe"));
Intent i=new Intent(Main.this,Tab.class);
//Intent in=new Intent(Main.this,TabActivity1.class);
i.putExtra(TAG_INGRIDIENTS,ingridients);
i.putExtra(TAG_RECIPE,name);
startActivity(i);
}
};
class recipeAdapter extends CursorAdapter {
recipeAdapter(Cursor c){
super(Main.this, c);
}
#Override
public void bindView (View row, Context ctxt, Cursor c)
{
recipeHolder holder = (recipeHolder)row.getTag();
holder.populateFrom(c, dbrecipelistHelper);
}
#Override
public View newView(Context ctxt, Cursor c, ViewGroup parent)
{
LayoutInflater inflater = getLayoutInflater();
View row=inflater.inflate(R.layout.list, parent, false);
recipeHolder holder = new recipeHolder(row);
row.setTag(holder);
return(row);
}
}
static class recipeHolder {
private TextView name=null;
recipeHolder(View row){
name=(TextView)row.findViewById(R.id.recipeText);
}
void populateFrom(Cursor c, recipelistHelper r){
name.setText(r.getName(c));
}
}
}
other method in this main class come from dbhelper class
Tab.java
import android.os.Bundle;
import android.app.Activity;
import android.app.TabActivity;
import android.content.Intent;
import android.view.Menu;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
public class Tab extends TabActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);
TabSpec tab1 = tabHost.newTabSpec("First Tab");
TabSpec tab2 = tabHost.newTabSpec("Second Tab");
TabSpec tab3 = tabHost.newTabSpec("Third tab");
tab1.setIndicator("Recipe");
tab1.setContent(new Intent(this,TabActivity1.class));
tab2.setIndicator("Facts");
tab2.setContent(new Intent(this,TabActivity2.class));
tab3.setIndicator("background");
tab3.setContent(new Intent(this,TabActivity3.class));
/** Add the tabs to the TabHost to display. */
tabHost.addTab(tab1);
tabHost.addTab(tab2);
tabHost.addTab(tab3);
}
}
TabActivity1
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class TabActivity1 extends Activity {
String recipeName = null;
String ingridients = null;
String procedure = null;
private TextView txtIngridients = null;
private TextView txtName = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
recipeName=this.getIntent().getStringExtra(Main.TAG_RECIPE);
ingridients=this.getIntent().getStringExtra(Main.TAG_INGRIDIENTS);
txtName=(TextView)findViewById(R.id.nameText);
txtIngridients=(TextView)findViewById(R.id.ingridientText);
txtName.setText(recipeName);
txtIngridients.setText(ingridients);
}
}
Pass bundle data in intent like:
Intent intent1 = new Intent(this,TabActivity1.class);
intent1.putExtra(Main.TAG_RECIPE, value);
intent1.putExtra(Main.TAG_INGRIDIENTS, value);
tab1.setContent(intent1);