I have a RecyclerView that displays a custom layout that is filled with two things:
An Image URL to display
A text name for the image
I query the SQLite database to get specific songs from the artist that is clicked on. I have this working, except for one thing.
I want to use the text name for the image (2) to be used as the variable in the query because the string is set to the value that I want to be used in the search query.
I cannot figure out how to access this variable.
Artists.java
package com.apps.robloxmusic;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import java.util.ArrayList;
public class Artists extends AppCompatActivity {
private static final String TAG = "Artists";
//Variables
private ArrayList<String> mNames = new ArrayList<>();
private ArrayList<String> mImagesUrls = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_artists);
Log.d(TAG, "onCreate: started.");
initImageBitmaps();
}
private void initImageBitmaps() {
Log.d(TAG, "initImageBitmaps: preparing bitmaps.");
mImagesUrls.add("https://cdn.blocktoro.com/wp-content/uploads/2019/07/bts-1097661412_1-e1562687430275-800x400.jpg");
mNames.add("BTS");
mImagesUrls.add("https://hdqwalls.com/download/post-malone-new-tattoo-2018-4k-lg-1920x1080.jpg");
mNames.add("Post Malone");
initRecyclerView();
}
private void initRecyclerView() {
Log.d(TAG, "initRecyclerView: preparing recycler view.");
RecyclerView recyclerView = findViewById(R.id.artistView);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(mNames, mImagesUrls, this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
}
RecyclerViewAdapter.java
package com.apps.robloxmusic;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.support.annotation.NonNull;
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.RelativeLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private static final String TAG = "RecyclerViewAdapter";
public ArrayList<String> mImagesNames = new ArrayList<>();
private ArrayList<String> mImages = new ArrayList<>();
private Context mContext;
public RecyclerViewAdapter(ArrayList<String> mImagesNames, ArrayList<String> mImages, Context mContext) {
this.mImagesNames = mImagesNames;
this.mImages = mImages;
this.mContext = mContext;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_artistlist, viewGroup, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
Log.d(TAG, "onBindViewerHolder: called.");
Glide.with(mContext)
.asBitmap()
.load(mImages.get(position))
.into(holder.artistImage);
holder.artistName.setText(mImagesNames.get(position));
holder.artistLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: clicked on:" + mImagesNames.get(position));
Intent intent = new Intent(mContext, BandView.class);
intent.putExtra("image_url", mImages.get(position));
//might not need this?
intent.putExtra("image_name", mImagesNames.get(position));
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return mImagesNames.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
CircleImageView artistImage;
TextView artistName;
RelativeLayout artistLayout;
public ViewHolder(#NonNull View itemView) {
super(itemView);
artistImage = itemView.findViewById(R.id.artistImage);
artistName = itemView.findViewById(R.id.artistName);
artistLayout = itemView.findViewById(R.id.artistLayout);
}
}
}
DatabaseAccess.java
private String allArtistSongs is what I'd like to set the text variable to. "BTS"; is just a placeholder.
package com.apps.robloxmusic;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
public class DatabaseAccess {
private SQLiteOpenHelper openHelper;
private SQLiteDatabase database;
private static DatabaseAccess instance;
private String allArtistSongs = "BTS";
/**
* Private constructor to avoid object creation from outside classes.
*
* #param context
*/
private DatabaseAccess(Context context) {
this.openHelper = new DatabaseOpenHelper(context);
}
/**
* Return a singleton instance of DatabaseAccess.
*
* #param context the Context
* #return the instance of DatabaseAccess
*/
public static DatabaseAccess getInstance(Context context) {
if (instance == null) {
instance = new DatabaseAccess(context);
}
return instance;
}
/**
* Open the database connection.
*/
public void open() {
this.database = openHelper.getWritableDatabase();
}
/**
* Close the database connection.
*/
public void close() {
if (database != null) {
this.database.close();
}
}
/**
* Read all songs from the database.
*
* #return a List of songs
*/
public List<String> getSongs() {
List<String> list = new ArrayList<>();
Cursor cursor = database.rawQuery("SELECT * FROM [Music_Codes]", null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
list.add(cursor.getString(0));
cursor.moveToNext();
}
cursor.close();
return list;
}
public List<String> getArtistSongs() {
List<String> list = new ArrayList<>();
Cursor cursor = database.rawQuery("SELECT * FROM [Music_Codes] WHERE Song LIKE ?", new String[] {"%"+ allArtistSongs+ "%"});
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
list.add(cursor.getString(0));
cursor.moveToNext();
}
cursor.close();
return list;
}
}
Where do you need to call getArtistSongs() ? I suspect you need to call this method in the new activity launched by the clickListener on the viewHolder.
if so, you can provide this string to the intent (image_name??). Then when the new activity starts up you can get the string from the intent and use it in the getArtistSongs().
getArtistSongs() need to have a parameter String for the query, something like
public List<String> getArtistSongs(String artist) {
List<String> list = new ArrayList<>();
Cursor cursor = database.rawQuery("SELECT * FROM [Music_Codes] WHERE Song LIKE ?", new String[] {"%"+ artist + "%"});
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
list.add(cursor.getString(0));
cursor.moveToNext();
}
cursor.close();
return list;
}
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'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();
}
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
Good afternoon guys, I am trying to fetch some data from the police data website.
Unfortunately, the application doesn't show any data saying "E/RecyclerView: No adapter attached; skipping layout".
I have attached the LatestCrimesActivity, adapter and the ListItem class.
Thank you for your help.
This is LatestCrimesActivity:
package com.example.cosmin.crimerate.Latest_crimes_api;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.cosmin.crimerate.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class LatestCrimesActivity extends AppCompatActivity {
private static final String URL_DATA = "https://data.police.uk/api/crimes-street/all-crime?poly=52.268,0.543:52.794,0.238:52.130,0.478&date=2017-01";
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<ListItem> listItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_latest_crimes);
recyclerView = (RecyclerView) findViewById(R.id.recyclerViewlatest);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems=new ArrayList<>();
loadRecyclerViewData();
}
private void loadRecyclerViewData() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading data...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET,
URL_DATA,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray("");
for (int i=0; i<array.length();i++){
JSONObject o = array.getJSONObject(i);
ListItem item = new ListItem(
o.getString("category"),
o.getString("location_type"),
o.getString("street"),
o.getString("status")
);
listItems.add(item);
}
adapter = new MyAdapter(listItems, getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Adapter:
package com.example.cosmin.crimerate.Latest_crimes_api;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.TextView;
import com.example.cosmin.crimerate.R;
import java.util.List;
/**
* Created by Cosmin on 25/11/2017.
*/
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<ListItem> listItems;
private Context context;
public MyAdapter(List<ListItem> listItems, LatestCrimesActivity latestCrimesActivity) {
this.listItems = listItems;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
ListItem listItem = listItems.get(position);
holder.textViewCat.setText(listItem.getCategory());
holder.textViewLoc.setText(listItem.getLocation());
holder.textViewStreet.setText(listItem.getStreet());
holder.textViewStatus.setText(listItem.getStatus());
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView textViewCat;
public TextView textViewLoc;
public TextView textViewStreet;
public TextView textViewStatus;
public ViewHolder(View itemView) {
super(itemView);
textViewCat = (TextView) itemView.findViewById(R.id.textViewCat);
textViewLoc = (TextView) itemView.findViewById(R.id.textViewLoc);
textViewStreet = (TextView) itemView.findViewById(R.id.textViewStreet);
textViewStatus = (TextView) itemView.findViewById(R.id.textViewStatus);
}
}
}
This is ListItem class:
package com.example.cosmin.crimerate.Latest_crimes_api;
/**
* Created by Cosmin on 25/11/2017.
*/
public class ListItem {
private String category;
private String location;
private String street;
private String status;
public ListItem (String category, String location, String street, String status){
this.category=category;
this.location=location;
this.street=street;
this.status=status;
}
public String getCategory (){
return category;
}
public String getLocation (){
return location;
}
public String getStreet (){
return street;
}
public String getStatus (){
return status;
}
}
Just try to change some lines. First set adapter before your api call.
recyclerView = (RecyclerView) findViewById(R.id.recyclerViewlatest);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems=new ArrayList<>();
adapter = new MyAdapter(listItems, getApplicationContext());
recyclerView.setAdapter(adapter);
Then when you received the answer, fill listItems, then call notifyDataSetChange() method of your adapter object.
i want to ask about OnClickListener. I called external database file[assets folder] in listview. I want to set onClicklistener at each item in listview. When listview item clicks, wanna appear a little fragment with data fields.I tried many sources but still not working.
Here is example fragment want to do.
enter image description here
Here is database structure.
enter image description here
Here is DatabaseHelper.java
package com.example.arlequina.sqlitefromassetexample.database;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.example.arlequina.sqlitefromassetexample.model.Product;
import java.util.ArrayList;
import java.util.List;
import java.sql.Blob;
/**
* Created by ARLEQUINA on 2/10/2017.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String dbname = "sample.db";
public static final String dblocation = "/data/data/com.example.arlequina.sqlitefromassetexample/databases/";
private Context mContext;
private SQLiteDatabase mDatabase;
public DatabaseHelper(Context context){
super(context, dbname, null, 1);
this.mContext = context;
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public void openDatabase(){
String dbPath = mContext.getDatabasePath(dbname).getPath();
if(mDatabase != null && mDatabase.isOpen()){
return;
}
mDatabase = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);
}
public void closeDatabase(){
if(mDatabase != null){
mDatabase.close();
}
}
public List<Product> getListProduct(){
Product product = null;
List<Product> productList = new ArrayList<>();
openDatabase();
Cursor cursor = mDatabase.rawQuery(" SELECT * FROM Product ", null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
product = new Product(cursor.getInt(0), cursor.getString(1), cursor.getString(2),cursor.getString(3));
productList.add(product);
cursor.moveToNext();
}
cursor.close();
closeDatabase();
return productList;
}
}
Here is ListProductAdapter.java
package com.example.arlequina.sqlitefromassetexample.adapter;
import android.content.Context;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.arlequina.sqlitefromassetexample.R;
import com.example.arlequina.sqlitefromassetexample.model.Product;
import org.w3c.dom.Text;
import java.util.List;
/**
* Created by ARLEQUINA on 2/10/2017.
*/
public class ListProductAdapter extends BaseAdapter{
private Context mContext;
private List<Product> mProductList;
public ListProductAdapter(Context mContext, List<Product> mProductList){
this.mContext = mContext;
this.mProductList = mProductList;
}
#Override
public int getCount() {
return mProductList.size();
}
#Override
public Object getItem(int position) {
return mProductList.get(position);
}
#Override
public long getItemId(int position) {
return mProductList.get(position).getId();
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
View v = View.inflate(mContext, R.layout.item_listview, null);
TextView tvName = (TextView)v.findViewById(R.id.tv_product_name);
TextView tvPrice = (TextView)v.findViewById(R.id.tv_product_price);
TextView tvDesc = (TextView)v.findViewById(R.id.tv_product_desc);
//ImageView tvImage = (ImageView)v.findViewById(R.id.tv_product_img);
tvName.setText(mProductList.get(position).getName());
tvPrice.setText(String.valueOf(mProductList.get(position).getPrice()) + " $");
tvDesc.setText(mProductList.get(position).getDesc());
// tvImage.setImageIcon(mProductList.get(position).getImage());
return v;
}
}
Here is MainActivity
package com.example.arlequina.sqlitefromassetexample;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.arlequina.sqlitefromassetexample.adapter.ListProductAdapter;
import com.example.arlequina.sqlitefromassetexample.database.DatabaseHelper;
import com.example.arlequina.sqlitefromassetexample.model.Product;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
/**
* Created by ARLEQUINA on 2/10/2017.
*/
public class MainActivity extends Activity {
private ListView lvProduct;
private ListProductAdapter adapter;
private List<Product> mProductList;
private DatabaseHelper mDBHelper;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvProduct = (ListView)findViewById(R.id.listview_product);
mDBHelper = new DatabaseHelper(this);
//Check exists database
File database = getApplicationContext().getDatabasePath(DatabaseHelper.dbname);
if(false == database.exists()){
mDBHelper.getReadableDatabase();
//Copy db
if(copyDatabase(this)){
Toast.makeText(this,"Copy database success", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Copy data error", Toast.LENGTH_SHORT).show();
return;
}
}
//Get product list in db when db exists
mProductList = mDBHelper.getListProduct();
//Init adapter
adapter = new ListProductAdapter(this,mProductList);
//Set adapter for listview
lvProduct.setAdapter(adapter);
}
private boolean copyDatabase(Context context){
try{
InputStream inputStream = context.getAssets().open(DatabaseHelper.dbname);
String outFileName = DatabaseHelper.dblocation + DatabaseHelper.dbname;
OutputStream outputStream = new FileOutputStream(outFileName);
byte[] buff = new byte[1024];
int length = 0;
while((length = inputStream.read(buff)) > 0){
outputStream.write(buff, 0, length);
}
outputStream.flush();
outputStream.close();
Log.v("MainActivity", "DB copied");
return true;
} catch(Exception e){
e.printStackTrace();
return false;
}
}
}
item_listview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:paddingBottom="5dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv_product_name"
android:text = "Name"
android:textColor="#4bb6d6"
android:textSize="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id = "#+id/tv_product_price"
android:text="100$"
android:textColor="#b30000"
android:textSize="18dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id = "#+id/tv_product_desc"
android:text="Description"
android:textSize="16dp"
android:textStyle="italic"/>
</LinearLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#d1d1d1">
<ListView
android:id = "#+id/listview_product"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:divider="#d1d1d1"
android:dividerHeight="10dp"></ListView>
</LinearLayout>
Product.java
package com.example.arlequina.sqlitefromassetexample.model;
import java.sql.Blob;
/**
* Created by ARLEQUINA on 2/10/2017.
*/
public class Product {
private int id;
private String name;
private String price;
private String desc;
//private Blob img;
public Product(int id, String name, String price, String desc){
this.id = id;
this.name = name;
this.price = price;
this.desc = desc;
//this.img = img;
}
public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getPrice(){
return price;
}
public void setPrice(String price){
this.price = price;
}
public String getDesc(){
return desc;
}
public void setDesc(String desc){
this.desc = desc;
}
}
Since your problem is make your list item clickable, you can use this after init listview in activity.
lvProduct.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
position is position of that clicked item in list. So you can get that item using mProductList.get(position)
After you can get that item, now it's time to show your item up. You can use custom dialog to make it like your demo (of cause you have to create 1 more xml):
Check section Custom Dialog in this official link: https://developer.android.com/guide/topics/ui/dialogs.html
You can use listview.setOnItemClickListener or v.setOnClickListener to solve your problem.That is the most basic ,man.