java.lang.NullPointerException in customize ArrayAdapter in android [duplicate] - android

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

Related

This error is coming while doing intent Cannot resolve method 'putExtra(java.lang.String, <lambda parameter>)'?

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 {
..........}

Android: Skipped 41 frames! The application may be doing too much work on its main thread

I'm really struggling to get my head round this thread thing. The below code is my mainactivity, I am just trying to test if my sqlite database is functioning by running a simple query to display a recipe.
Currently the app just runs the main screen but nothing else works. What can I do to get this working?
I can provide further code/snippets if requested. Thank you
package com.stu54259.plan2cook;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import com.google.android.material.bottomappbar.BottomAppBar;
import com.synnapps.carouselview.CarouselView;
import com.synnapps.carouselview.ImageListener;
public class MainActivity extends AppCompatActivity {
CarouselView carouselView;
int[] sampleImages = {R.drawable.avocado_salad, R.drawable.chicken_tikka_curry, R.drawable.turkey_taco_bowls};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpBottomAppBar();
carouselView = findViewById(R.id.recipeImage);
carouselView.setPageCount(sampleImages.length);
carouselView.setImageListener(imageListener);
findViewById(R.id.fab).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Create Recipe Clicked.", Toast.LENGTH_SHORT).show();
}
});
GridView gv = findViewById(R.id.gridview);
gv.setAdapter(new SetImageAdapter(this));
}
ImageListener imageListener = new ImageListener() {
#Override
public void setImageForPosition(int position, ImageView imageView) {
imageView.setImageResource(sampleImages[position]);
}
};
private void setUpBottomAppBar() {
BottomAppBar bottomAppBar = findViewById(R.id.bar);
setSupportActionBar(bottomAppBar);
Log.d("appbar setup", "yes");
bottomAppBar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.recipes:
Toast.makeText(MainActivity.this, "Recipes clicked.", Toast.LENGTH_LONG).show();
Log.d("Intent", "clicked ");
Intent intent = new Intent(MainActivity.this, Recipe.class);
startActivity(intent);
break;
case R.id.shoppingList:
Toast.makeText(MainActivity.this, "Shopping List clicked", Toast.LENGTH_SHORT).show();
break;
}
return false;
}
});
}
/* #Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.bottom_nav_primary, menu);
return super.onCreateOptionsMenu(menu);
}*/
}
Logcat
Skipped 41 frames! The application may be doing too much work on its main thread.
Recipe.java
package com.stu54259.plan2cook;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.tabs.TabLayout;
import com.stu54259.plan2cook.Model.RecipeList;
import com.stu54259.plan2cook.database.DatabaseManager;
import java.util.ArrayList;
import java.util.List;
public class Recipe extends MainActivity {
TabLayout tabLayout;
ImageView recipeImage;
TextView descriptionText, courseText, servingsText, costText, caloriesText, methodText;
RecyclerView listIngredient;
SQLiteDatabase db;
String search_name, selectQuery;
Cursor c;
RecyclerViewAdapter adapterRecipe;
List<RecipeList> itemRecipe = new ArrayList<>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recipe);
//search_name = getIntent().getStringExtra("NAME");
search_name = "Speedy chicken couscous";
//recyclerview Recipe
adapterRecipe = new RecyclerViewAdapter(this, itemRecipe);
listIngredient = findViewById(R.id.listIngredient);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this,
LinearLayoutManager.VERTICAL, false);
listIngredient.setLayoutManager(mLayoutManager);
listIngredient.setItemAnimator(new DefaultItemAnimator());
listIngredient.setAdapter(adapterRecipe);
loadRecipe();
}
public void loadRecipe() {
itemRecipe.clear();
db = (new DatabaseManager(this).getWritableDatabase());
String selectQuery = "";
selectQuery = selectQuery + "SELECT A.ingredient_quantity, B.measurement_name, B.ingredient_name, B.description " +
"FROM TABLE_QUANTITY JOIN TABLE_INGREDIENT ON A.ingredient = B.ingredient_name";
c = db.rawQuery(selectQuery, new String[]{"%" + search_name + "%"});
if (c.moveToFirst()) {
do {
RecipeList recipeList = new RecipeList();
recipeList.setId(c.getInt(c.getColumnIndex("COL_ID")));
recipeList.setIngredient_amount(c.getString(c.getColumnIndex("COL_INGREDIENT_QUANTITY")));
recipeList.setMeasurement_name(c.getString(c.getColumnIndex("COL_MEASUREMENT_NAME")));
recipeList.setIngredient_name(c.getString(c.getColumnIndex("COL_INGREDIENT_NAME")));
recipeList.setDescription(c.getString(c.getColumnIndex("COL_DESCRIPTION")));
itemRecipe.add(recipeList);
} while (c.moveToNext());
c.close();
}
}
}
Recyclerview adapter
package com.stu54259.plan2cook;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.stu54259.plan2cook.Model.RecipeList;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private List<RecipeList> itemRecipe;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
// data is passed into the constructor
RecyclerViewAdapter(Context context, List<RecipeList> data) {
this.mInflater = LayoutInflater.from(context);
this.itemRecipe = data;
}
// inflates the row layout from xml when needed
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.fragment_item, parent, false);
return new ViewHolder(view);
}
// binds the data to the TextView in each row
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.myTextView.setText(itemRecipe.get(position).getIngredient_amount());
holder.myTextView.setText(itemRecipe.get(position).getMeasurement_name());
holder.myTextView.setText(itemRecipe.get(position).getIngredient_name());
holder.myTextView.setText(itemRecipe.get(position).getDescription());
}
// total number of rows
#Override
public int getItemCount() {
return itemRecipe.size();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView myTextView;
ViewHolder(View itemView) {
super(itemView);
myTextView = itemView.findViewById(R.id.listIngredient);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// allows clicks events to be caught
void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
You could try making the DB calls in an AsyncTask
AsyncTask getRecipesTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... voids) {
loadRecipe();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//TODO update adapter with new items
}
};
And in onCreate
Replace the call to loadRecipe() with getRecipesTask.execute()
public class Recipe extends MainActivity {
TabLayout tabLayout;
ImageView recipeImage;
TextView descriptionText, courseText, servingsText, costText, caloriesText, methodText;
RecyclerView listIngredient;
SQLiteDatabase db;
String search_name, selectQuery;
Cursor c;
RecyclerViewAdapter adapterRecipe;
List<RecipeList> itemRecipe = new ArrayList<>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recipe);
//search_name = getIntent().getStringExtra("NAME");
search_name = "Speedy chicken couscous";
//recyclerview Recipe
adapterRecipe = new RecyclerViewAdapter(this);
listIngredient = findViewById(R.id.listIngredient);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this,
LinearLayoutManager.VERTICAL, false);
listIngredient.setLayoutManager(mLayoutManager);
listIngredient.setItemAnimator(new DefaultItemAnimator());
listIngredient.setAdapter(adapterRecipe);
getRecipesTask.execute();
}
public void loadRecipe() {
itemRecipe.clear();
db = (new DatabaseManager(this).getWritableDatabase());
String selectQuery = "";
selectQuery = selectQuery + "SELECT A.ingredient_quantity, B.measurement_name, B.ingredient_name, B.description " +
"FROM TABLE_QUANTITY JOIN TABLE_INGREDIENT ON A.ingredient = B.ingredient_name";
c = db.rawQuery(selectQuery, new String[]{"%" + search_name + "%"});
if (c.moveToFirst()) {
do {
RecipeList recipeList = new RecipeList();
recipeList.setId(c.getInt(c.getColumnIndex("COL_ID")));
recipeList.setIngredient_amount(c.getString(c.getColumnIndex("COL_INGREDIENT_QUANTITY")));
recipeList.setMeasurement_name(c.getString(c.getColumnIndex("COL_MEASUREMENT_NAME")));
recipeList.setIngredient_name(c.getString(c.getColumnIndex("COL_INGREDIENT_NAME")));
recipeList.setDescription(c.getString(c.getColumnIndex("COL_DESCRIPTION")));
itemRecipe.add(recipeList);
} while (c.moveToNext());
c.close();
}
}
AsyncTask getRecipesTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... voids) {
loadRecipe();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
adapterRecipe.setItems(itemRecipe);
}
};
}
I'm not exactly sure what your adapter looks like but trying something like this:
Probably setItems could be something like in the Adapter
public void setItems(List<Recipe> items) {
this.items = items;
notifyDataSetChanged();
}

How to customize Adapter for SwipeCard?

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.

Retrieve data from SQLite in RecyclerView inside fragment

I have an activity that contain custom Tablayout.
the Tablayot has pageViewer and link to a fragment.
I want to show data from my SQLite database in RecyclerView in fragment.
this is my codes:
DatabaseHelper.java:
package ir.shirazmetro;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = "DatabaseHelper";
public static final String DATABASE_NAME = "MetroDB.db";
public static final String TABLE_NAME = "estation";
public static final String COL_1 = "station";
public static final String COL_2 = "time";
public static final String COL_3 = "line";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (COL_1,COL_2,COL_3)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String station, String time, String line) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_2, time);
long result = db.insert(TABLE_NAME, null, contentValues);
if (result == -1)
return false;
else
return true;
}
public Cursor getData() {
SQLiteDatabase db = this.getWritableDatabase();
return db.rawQuery("select "+COL_2+" from " + TABLE_NAME, null);
}
}
My activity(station.java):
package ir.shirazmetro.views.activities;
import android.content.Intent;
import android.support.v4.view.ViewPager;
import android.support.design.widget.TabLayout;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
import ir.shirazmetro.DatabaseHelper;
import ir.shirazmetro.R;
import ir.shirazmetro.other.components.ButtonCell;
import ir.shirazmetro.other.components.TextViewCell;
import ir.shirazmetro.views.adapters.BasePagerAdapter;
import ir.shirazmetro.views.adapters.MoviesAdapter;
public class estation extends BaseActivity {
Toolbar mToolbar;
private TabLayout tbLayout;
private ViewPager vPager;
private List<DatabaseHelper> movies = new ArrayList<DatabaseHelper>();
private RecyclerView recyclerView;
private MoviesAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_estation);
mToolbar = findViewById(R.id.tlbr1);
setSupportActionBar(mToolbar);
initView();
setupWithViewPager();
tbLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
recyclerView = findViewById(R.id.myRecycler);
adapter = new MoviesAdapter(movies);
recyclerView.setLayoutManager(new LinearLayoutManager(estation.this));
recyclerView.setAdapter(adapter);
DatabaseHelper getData = (DatabaseHelper) new DatabaseHelper(this).getData();
movies.add(getData);
adapter.notifyDataSetChanged();
}
}
private void setupWithViewPager() {
BasePagerAdapter basePagerAdapter = new BasePagerAdapter(this, getSupportFragmentManager());
vPager.setAdapter(basePagerAdapter);
tbLayout.setupWithViewPager(vPager);
}
private void initView() {
vPager = findViewById(R.id.view_pager);
tbLayout = findViewById(R.id.tab_layout);
backBtn = findViewById(R.id.backBtn);
backBtn.setOnClickListener((View.OnClickListener) this);
}
}
and this code is my Adapter:
package ir.shira.views.adapters;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
import ir.shira.DatabaseHelper;
import ir.shira.R;
import ir.shira.models.movie;
public class MoviesAdapter extends RecyclerView.Adapter<MoviesAdapter.MovieViewHolder> {
private List<movie> movies;
private Context context;
public MoviesAdapter(List<DatabaseHelper> movies) {
movies = movies;
}
#NonNull
#Override
public MovieViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_to_dastgheyb,parent,false);
return new MovieViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MovieViewHolder holder, int position) {
holder.txtTime.setText(movies.get(position).getTime());
}
#Override
public int getItemCount() {
return movies.size();
}
public class MovieViewHolder extends RecyclerView.ViewHolder
{
public TextView txtTime;
public MovieViewHolder(View itemView)
{
super(itemView);
txtTime = itemView.findViewById(R.id.textView);
}
}
}
my app crash when I run the project, any ideas?
movies.get(position).getTime() retrieve DatabaseHelper, I think it is checked exception.
You are making mistake hear
When You creating List Obj.
private List<DatabaseHelper> movies = new ArrayList<DatabaseHelper>();
//.. List Type DatabaseHelper But You want movie ? so change this line to like this
private List<movie> movies = new ArrayList<movie>();
//movie is your model

Passing listview array strings to viewtext in another activity

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

Categories

Resources