CursorLoader not populating ListView [HELP] - sqlite

My app uses a cursorloader to populate sqlite data into a ListView. Actually, the cursorloader should only populate one column (COLUNM_NAME_SITE) from the DB into the listview. The issue I have is once information is inserted in the db, a list item is created ( I can tell by the row lines shown every time data is inserted) but no text is shown in the listview the listview is basically blank. I believe this also makes the app crash once the list view item is clicked.
I assume my FROM and TO arrays and Cursor Adapter are created properly but I can be wrong. Could the issue be with my Layout? Iā€™m not sure but am hoping someone will take a in depth look at my code and let me know where I went wrong.
I do not receive any errors until I click on the blank listview item.
Loader Class:
public class LoginList extends FragmentActivity implements AdapterView.OnItemClickListener, OnClickListener, LoaderManager.LoaderCallbacks<Cursor> {
private ListView loginList;
private Button webLogin;
private SimpleCursorAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_listview);
loginList = (ListView)findViewById(R.id.loginlist);
loginList.setOnItemClickListener(this);
webLogin = (Button)findViewById(R.id.button3);
webLogin.setOnClickListener(this);
//Specify fileds to display in the list
String[] from = new String[] { ListProvider.COLUMN_NAME_SITE };
//Bind fields to listview
int[] to = new int[] {R.id.loginlist };
// Create CursorAdapter and set it to display
adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, null, from, to);
loginList.setAdapter(adapter);
getSupportLoaderManager().initLoader(0, null, this);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Selected ID :" + arg2, Toast.LENGTH_SHORT).show();
Intent updateDeleteLoginInfo = new Intent (this, UpdateDeleteLoginList.class);
Cursor clickedObject = (Cursor)loginList.getItemAtPosition(arg2);
Bundle loginBundle = new Bundle();
loginBundle.putString("clickedWebSite",((LoginDetails) clickedObject).getsName());
loginBundle.putString("clickedWebAddress",((LoginDetails) clickedObject).getwUrl());
loginBundle.putString("clickedUserName",((LoginDetails) clickedObject).getuName());
loginBundle.putString("clickedPassWord",((LoginDetails) clickedObject).getpWord());
loginBundle.putString("clickedNotes",((LoginDetails) clickedObject).getlNotes());
updateDeleteLoginInfo.putExtras(loginBundle);
startActivityForResult(updateDeleteLoginInfo, 0);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent webLoginIntent = new Intent (this, LoginPlusActivity.class);
startActivity(webLoginIntent);
}
#Override
public Loader<Cursor> onCreateLoader(int ignored, final Bundle args) {
return new CursorLoader(this, ListProvider.CONTENT_URI, null, null, null, null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
adapter.swapCursor(cursor);
}
#Override
public void onLoaderReset (Loader<Cursor> loader) {
adapter.swapCursor(null);
}
}
Layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ns="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="#+id/loginlist"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/button3"
android:layout_alignParentTop="true" />
<Button
android:id="#+id/button3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:text="ADD" />
</RelativeLayout>
Database:
//Database Columns
public static final String COLUMN_ROWID = "_id";
public static final String COLUMN_NAME_SITE = "sName";
public static final String COLUMN_NAME_ADDRESS = "wUrl";
public static final String COLUMN_NAME_USERNAME = "uName";
public static final String COLUMN_NAME_PASSWORD = "pWord";
public static final String COLUMN_NAME_NOTES = "lNotes";
// Database related Constants
public static final String DATABASE_NAME = "SiteLogindb";
public static final int DATABASE_VERSION = 2;
public static final String DSTORE_CREATE = "create table if not exists " +
TABLE_NAME_INFOTABLE + " ("+ COLUMN_ROWID + " integer primary key autoincrement,"
+ COLUMN_NAME_SITE + " text not null,"
+ COLUMN_NAME_ADDRESS + " text not null,"
+ COLUMN_NAME_USERNAME + " text not null,"
+ COLUMN_NAME_PASSWORD + " text not null,"
+ COLUMN_NAME_NOTES + " text not null);";

A different way you can accomplish this is to extend ListActivity and implement LoaderManager.LoaderCallbacks.
public class LoginActivity extends ListActivity implements LoaderManager.LoaderCallbacks<Cursor> {...
There is a good 4 part tutorial on this over at the Android Design Patterns blog.

Related

Getting ERROR: When im clickingone of my item in my Recyclerview

I want to make a theme app and I have a home page where I am trying to show some theme As a category, and there I am using RecyclerView for each category, and my Recyclerview get data from firebase real-time database where I use one image link, one text, and one URL which I want to show in my WebView through this code
Intent intent = new Intent(v.getContext().getApplicationContext(), BrowserActivity.class);
intent.putExtra("url_E", url);
v.getContext().startActivity(intent);
but the problem is all items are fetching perfectly from firebase, and showing the correct title and image each and every item of my Recyclerview but if I click the 6 or 7 items from Recyclerview then the link was not loaded correctly, The link that is loading is not that item link, The link is being replaced with another item link and that wrong link I can find in the database from another item in the same category.
****Please Help Me
If I add a Toast.makeText(, url, Toast.LENGTH_SHORT).show(); with setOnClickListener then the correct link is showing in Toast but the load link on the webpage is wrong same!!!! -- -- šŸ¤¦ā€ā™€ļøšŸ¤¦ā€ā™‚ļøšŸ¤¦ā€ā™‚ļøšŸ¤¦ā€ā™‚ļøšŸ¤¦ā€ā™‚ļø
HErer is my activity :
enter image description here
layout:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="end"
android:orientation="horizontal">
<ImageView
android:layout_width="17dp"
android:layout_height="17dp"
android:layout_gravity="bottom"
android:layout_marginStart="5dp"
android:layout_marginEnd="10sp"
android:src="#drawable/theme_review" />
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/RVModern"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="5dp"
android:layout_marginBottom="8dp"
android:paddingStart="10dp" />
MainFragemnt:
DataRef = FirebaseDatabase.getInstance().getReference("ThemeByStyle");
// Modern
DataRef.child("ModernTheme").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot npsnapshot : dataSnapshot.getChildren()) {
ListDataMODERN = npsnapshot.getValue(ListData.class);
listData1.add(ListDataMODERN);
}
homeAdapter = new HomeAdapter(listData1);
RVModern.setAdapter(homeAdapter);
Collections.reverse(listData1);
RVModern.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
homeAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
adapter:
{
private final List<ListData> listData;
CardView ClickItem;
String url;
ImageView post_img;
TextView post_title;
Dialog OkBox;
public HomeAdapter (List<ListData> listData) {
this.listData = listData;
}
#SuppressLint("WrongConstant")
#NonNull
#Override
public HomeAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_body_home,parent,false);
ClickItem = view.findViewById(R.id.cardview);
OkBox = new Dialog(view.getContext());
return new HomeAdapter.ViewHolder(view);
}/**************************************************************************/
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final ListData listdata = listData.get(position);
holder.setUrlss(listdata.getUrls());
holder.setTitle(listdata.getTitle());
holder.setImgOne(listdata.getImg1());
// url = listdata.getUrls();
}
#Override
public int getItemCount () {
return listData.size();
// return 2;
}
public class ViewHolder extends RecyclerView.ViewHolder {
View vv;
public ViewHolder(View itemView) {
super(itemView);
vv = itemView;
}
public void setTitle(String title) {
post_title = vv.findViewById(R.id.post_title);
post_title.setText(title);
}
public void setImgOne(String imgone) {
post_img = vv.findViewById(R.id.imgOne);
Glide
.with(vv)
.load(imgone)
.into(post_img);
}
public void setUrlss (String setUrls) {
TextView urltxt = vv.findViewById(R.id.urltxt);
urltxt.setText(setUrls);
url = setUrls;
ClickItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext().getApplicationContext(), BrowserActivity.class);
intent.putExtra("url_E", url);
v.getContext().startActivity(intent);
/* Okbox();
ClipboardManager clipboard = (ClipboardManager) v.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label", setUrlXX);
clipboard.setPrimaryClip(clip);
Toast.makeText(v.getContext().getApplicationContext(), setUrlXX, Toast.LENGTH_SHORT).show();*/
}
});
}
}
private void Okbox() {
OkBox.setContentView(R.layout.ok);
Window window = OkBox.getWindow();
window.setLayout(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
window.setGravity(Gravity.TOP);
TextView t0title = OkBox.findViewById(R.id.t0title);
t0title.setText(url);
OkBox.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
OkBox.show();
}
}
HELP ME PLZ PLZ PLZ PLZ PLZ PLZ PLZ PLZ

Android Spinner: Populate second and thrid spinner based on first spinner filter

Same question header is available but requirement is different.
First spinner selection should load from database and second spinner and third spinner should change based one first spinner selection.
Current:
-
As i can see there is something wrong in sql query which i am unable to find.
Issue :
Spinner1 should display ignore the duplication instead of two P1 it should display like P1,P2,N1.
Spinner2 should display all records which relevant to P1 whereas its shows only one record
Requirement :
Second spinner and third spinner should populate data based on first spinner whereas challenge is second spinner should display all data which is matched by spinner1.
Layout:SpinnerEx4Activity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical">
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="8dip" android:text="#string/lblAcc" />
<Spinner android:id="#+id/spinner4" android:layout_width="138dp" android:layout_height="wrap_content" android:drawSelectorOnTop="true" />
<Spinner android:id="#+id/spinner1" android:layout_width="368dp" android:layout_height="wrap_content" android:drawSelectorOnTop="true" android:layout_toRightOf="#+id/spinner4" android:layout_alignBaseline="#+id/spinner4" />
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="8dip" android:text="#string/lblSubAcc" />
<Spinner android:id="#+id/spinner2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="10dip" android:layout_marginLeft="8dip" android:layout_marginRight="8dip" />
<TextView android:id="#+id/textView2" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Visit Day" />
<CheckBox android:id="#+id/checkBox2" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Sunday" />
<CheckBox android:id="#+id/checkBox3" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Monday" />
<CheckBox android:id="#+id/checkBox4" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Tuesday" />
<CheckBox android:id="#+id/checkBox5" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Wednesday" />
<CheckBox android:id="#+id/checkBox6" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Thursday" />
<CheckBox android:id="#+id/checkBox" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Saturday" />
<CheckBox android:id="#+id/checkBox7" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Outlet is Closed" />
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal">
<TextView android:id="#+id/textView6" android:layout_width="match_parent" android:layout_height="wrap_content" android:scrollHorizontally="false" android:text="Total Outlet" android:textSize="10dp" android:textStyle="bold" android:layout_weight="1" />
<TextView android:id="#+id/textView7" android:layout_width="match_parent" android:layout_height="wrap_content" android:scrollHorizontally="false" android:text="T Outlet" android:textSize="19dp" android:textStyle="bold" android:layout_weight="1" />
<TextView android:id="#+id/textView9" android:layout_width="match_parent" android:layout_height="wrap_content" android:scrollHorizontally="false" android:text="Completed Outlet" android:textSize="10dp" android:textStyle="bold" android:layout_weight="1"
/>
<TextView android:id="#+id/textView8" android:layout_width="match_parent" android:layout_height="wrap_content" android:scrollHorizontally="false" android:text="C.Outlet" android:textSize="19dp" android:textStyle="bold" android:layout_weight="1" />
</LinearLayout>
<Spinner android:id="#+id/spinner3" android:layout_width="match_parent" android:layout_height="wrap_content" />
<EditText android:id="#+id/input_label" android:layout_width="match_parent" android:layout_height="0dp" android:ems="10" android:inputType="textPersonName" />
<Button android:id="#+id/btn_add" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Save" />
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal">
<Button android:id="#+id/btnexport" android:layout_width="match_parent" android:layout_height="wrap_content" android:scrollHorizontally="false" android:text="Download" android:textSize="15dp" android:textStyle="bold" android:layout_weight="1" />
<Button android:id="#+id/btn_send_mail" android:layout_width="match_parent" android:layout_height="wrap_content" android:scrollHorizontally="false" android:text="Send" android:textSize="15dp" android:textStyle="bold" android:layout_weight="1" />
</LinearLayout>
<Button android:id="#+id/btn" android:layout_width="match_parent" android:layout_height="wrap_content" android:scrollHorizontally="false" android:text="Import" android:textSize="15dp" android:textStyle="bold" android:layout_weight="1" />
</LinearLayout>
MainActivity.Java
public class SpinnerEx4Activity extends AppCompatActivity {
Spinner s1,s2,s3,s4;
Button btnAdd;
Button send;
Button ok;
Button btn_send_mail;
private Button btnexport;
EditText inputLabel;
TextView tex,tex1;
DatabaseHandler dbhndlr;
Cursor spinner1csr, spinner2csr, spinner3csr;
SimpleCursorAdapter sca, sca2,sca3;
long spinner1_selected = 0;
long spinner4_selected = 0;
long spinner3_selected = 0;
CheckBox ck1,ck2,ck3,ck4,ck5,ck6,ck7,ck8;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner_ex4);
s1 = (Spinner)findViewById(R.id.spinner1);
s2 = (Spinner)findViewById(R.id.spinner2);
s3 = (Spinner)findViewById(R.id.spinner3);
s4 = (Spinner)findViewById(R.id.spinner4);
btnAdd = (Button) findViewById(R.id.btn_add);
inputLabel = (EditText) findViewById(R.id.input_label);
dbhndlr = new DatabaseHandler(this);
ck1=(CheckBox) findViewById(R.id.checkBox);
ck2=(CheckBox)findViewById(R.id.checkBox2);
ck3=(CheckBox)findViewById(R.id.checkBox3);
ck4=(CheckBox)findViewById(R.id.checkBox4);
ck6=(CheckBox) findViewById(R.id.checkBox5);
ck7=(CheckBox)findViewById(R.id.checkBox6);
ck8=(CheckBox)findViewById(R.id.checkBox7);
final Button btnexport = (Button) findViewById(R.id.btnexport);
btn_send_mail = (Button) findViewById(R.id.btn_send_mail);
ok = (Button) findViewById(R.id.btn);
loadSpinnerData();
TextView tex = (TextView) findViewById(R.id.textView7);
TextView tex1 = (TextView) findViewById(R.id.textView8);
if (DatabaseUtils.queryNumEntries(dbhndlr.getWritableDatabase(),DatabaseHandler.TABLE_LABELS) < 1) {
dbhndlr.insertlabel("1" ,"P1","Henry","9001234");
dbhndlr.insertlabel("2","P1","Malik","9004567");
dbhndlr.insertlabel("3","P2","ermarket","900356");
dbhndlr.insertlabel("4","N1","Veli","9003456");
}
if (DatabaseUtils.queryNumEntries(dbhndlr.getWritableDatabase(),DatabaseHandler.TABLE_LABELS1) < 2) {
dbhndlr.insertlabel12("14","0001 Daily");
dbhndlr.insertlabel12("21","0007 Weekly");
dbhndlr.insertlabel12("34","0014 Days");
dbhndlr.insertlabel12("44","0021 Days");
dbhndlr.insertlabel12("54","0028 Days");
}
spinner1csr = dbhndlr.getAllLabelsAsCursor();
s1.setAdapter(sca);
sca3 = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,spinner1csr,
new String[]{DatabaseHandler.KEY_ID1},
new int[]{android.R.id.text1},
0
);
s4.setAdapter(sca3);
class SendMail extends AsyncTask <String, Integer, Void> {
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(SpinnerEx4Activity.this, "Please wait", "Sending mail", true, false);
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
progressDialog.dismiss();
}
protected Void doInBackground(String... params) {
Mail m = new Mail("d.com", "t3e");
String[] toArr = {"fdm.bh"};
m.setTo(toArr);
m.setFrom("owMobile");
m.setSubject("This is emaster Data Application");
m.setBody("Find attached excoute,Thank you.");
try {
m.addAttachment(Environment.getExternalStorageDirectory()+"/android/data/com.example.ok.myapplication/files/w.csv");
if(m.send()) {
Toast.makeText(SpinnerEx4Activity.this, "Email was sent successfully.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(SpinnerEx4Activity.this, "Email was not sent.", Toast.LENGTH_LONG).show();
}
} catch(Exception e) {
Log.e("MailApp", "Could not send email", e);
}
return null;
}
}
});
///////////////////////////////
s4.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id1) {
spinner4_selected = id1;
spinner1csr = dbhndlr.getByRowid(spinner4_selected);
spinner2csr = dbhndlr.getByRowid(spinner4_selected);
sca.swapCursor(spinner1csr);
sca2.swapCursor(spinner2csr);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
sca = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
spinner1csr,
new String[]{DatabaseHandler.KEY_NAME},
new int[]{android.R.id.text1},
0
);
sca2 = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
spinner1csr,
new String[]{DatabaseHandler.KEY_ID},
new int[]{android.R.id.text1},
0
);
s1.setAdapter(sca);
s2.setAdapter(sca2);
private void loadSpinnerData() {
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
List<String> lables = db.getAllLabels();
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
dataAdapter1
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
/
s3.setAdapter(dataAdapter1);
}
#Override
public void onDestroy() {
spinner1csr.close();
spinner2csr.close();
spinner3csr.close();
super.onDestroy();
}
protected Void doInBackground(String... params) {
Mail m = new Mail("d.com", "4#");
String[] toArr = {"d.gw"};
m.setTo(toArr);
m.setFrom("Mata");
m.setSubject("This is tion");
m.setBody("Find ute,Thank you.");
try {
m.addAttachment(Environment.getExternalStorageDirectory() + "/Android/data/com.example.ok.myapplication/files/ce.csv");
if (m.send()) {
Toast.makeText(SpinnerEx4Activity.this, "Email was sent successfully.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(SpinnerEx4Activity.this, "Email was not sent.", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Log.e("MailApp", "Could not send email", e);
}
return null;
}
}
Database
public class DatabaseHandler extends SQLiteOpenHelper {
// Database Version
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "spinnerExample";
private static String DB_PATH = "/data/data/com.example.ok.myapplication/databases/";
private final Context myContext;
private SQLiteDatabase myDataBase;
// Database Name
// Labels table name
public static final String TABLE_LABELS = "labels"; //<<<< Made public
public static final String TABLE_LABELS1= "labels1";
public static final String TABLE_LABELS2= "labels2";
// Labels Table Columns names
public static final String KEY_ID4 = "input_label";
public static final String KEY_ID12 = "id2"; //<<<< Made public
public static final String KEY_ID = "id";
public static final String KEY_99 = "sno"; //<<<< Made public//<<<< Made public
public static final String KEY_NAME = "name"; //<<<< made public
public static final String KEY_ID1 = "id1"; //<<<< Made public
public static final String KEY_NAME1 = "name1";
public static final String KEY_1 = "number"; //<<<< Made public
public static final String KEY_2 = "outletname"; //<<<< made public
public static final String KEY_3 = "sunday"; //<<<< Made public
public static final String KEY_4 = "monday";
public static final String KEY_5 = "tuesday";
public static final String KEY_6 = "wednesday";
public static final String KEY_7 = "thursday";
public static final String KEY_8 = "saturday";
public static final String KEY_9 = "closed";
public static final String KEY_10 = "calling";
public static final String KEY_11 = "id3";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
myDataBase = this.getWritableDatabase();
this.myContext = context;
Log.e("Path 1", DB_PATH);
}
// Creating Tables
public void openDataBase() throws SQLException {
String myPath = DB_PATH + DATABASE_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
#Override
public void onCreate(SQLiteDatabase db) {
boolean dbExist = checkDataBase();
// Category table create query
String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("+ KEY_99 + " INTEGER,"
+ KEY_ID1 + " TEXT," + KEY_ID + " TEXT," + KEY_NAME + " TEXT)";
String CREATE_CATEGORIES_TABLE1 = "CREATE TABLE " + TABLE_LABELS1 + "("
+ KEY_ID1+ " TEXT," + KEY_NAME1+ " TEXT)";
String CREATE_CATEGORIES_TABLE2 = "CREATE TABLE " + TABLE_LABELS2 + "("
+ KEY_11+ " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_1+ " TEXT," + KEY_2+ " TEXT," + KEY_3+ " INTEGER," + KEY_4+ " INTEGER,"+ KEY_5+ " INTEGER," + KEY_6+ " INTEGER," + KEY_7+ " INTEGER," + KEY_8+ " INTEGER," + KEY_9+ " INTEGER," + KEY_10+ " TEXT)";
db.execSQL(CREATE_CATEGORIES_TABLE);
db.execSQL(CREATE_CATEGORIES_TABLE1);
db.execSQL(CREATE_CATEGORIES_TABLE2);
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DATABASE_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
private void copyDataBase() throws IOException {
InputStream myInput = myContext.getAssets().open(DATABASE_NAME);
String outFileName = DB_PATH + DATABASE_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[10];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS1);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS2);
// Create tables again
onCreate(db);
}
// Added for adding new data
public void insertlabel(String text,String id1,String id, String label) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(KEY_99,text);
cv.put(KEY_ID1,id1);
cv.put(KEY_ID,id);
cv.put(KEY_NAME,label);
db.insert(TABLE_LABELS,null,cv);
db.close();
}
public void insertlabel12(String id1, String label1) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv1 = new ContentValues();
cv1.put(KEY_ID1,id1);
cv1.put(KEY_NAME1,label1);
db.insert(TABLE_LABELS1,null,cv1);
db.close();
}
/**
* Inserting new lable into lables table
* */
public void insertLabel(String message1, String message2,String message3,String message4,String message5,String message6,String message7,String message8,String message9,String message10){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_1, message1);
values.put(KEY_2, message2);
values.put(KEY_10,message10);
values.put(KEY_4,message4);
values.put(KEY_5,message5);
values.put(KEY_6,message6);
values.put(KEY_7,message7);
values.put(KEY_3,message3);
values.put(KEY_9,message9);
values.put(KEY_8,message8);
// Inserting Row
db.insert(TABLE_LABELS2, null, values);
db.close(); // Closing database connection
}
public void insertLabel1(String label){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME1, label);
// Inserting Row
db.insert(TABLE_LABELS1, null, values);
db.close(); // Closing database connection
}
public void insertLabel2(String label){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME1, label);
values.put(KEY_10, label);
values.put(KEY_ID, label);
db.insert(TABLE_LABELS2, null, values);
db.close(); // Closing database connection
}
public List<String> getAllLabels(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_LABELS1;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
public List<String> andrew(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_LABELS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning lables
return labels;
}
public Cursor getAllEntries(){
String selectQuery = "SELECT count (*) FROM " + TABLE_LABELS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cur = db.rawQuery(selectQuery, null);
return cur;
}
public Cursor getAllEntries1(){
String selectQuery = "SELECT count (*) FROM " + TABLE_LABELS2;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cur1 = db.rawQuery(selectQuery, null);
return cur1;
}
public List<String> getAllLabels1(){
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT count (*) FROM " + TABLE_LABELS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor1 = db.rawQuery(selectQuery, null);
final ArrayList<String> row1 = new ArrayList<String>();
// looping through all rows and adding to list
if (cursor1.moveToFirst()) {
do {
labels.add(cursor1.getString(1));
} while (cursor1.moveToNext());
}
// closing connection
cursor1.close();
db.close();
// returning lables
return labels;
}
// Added to get Cursor for Simple CursorAdapter
public Cursor getAllLabelsAsCursor() {
String[] columns = new String[]{"rowid AS _id, *"}; // Need _id column for SimpleCursorAdapter
return this.getWritableDatabase().query(TABLE_LABELS,columns,null,null,null,null,null);
}
public Cursor getAllLabelsExceptedSelected(long selected) {
String[] columns = new String[]{"rowid AS _id, *"};
String whereclause = "rowid <> ?";
String[] whereargs = new String[]{String.valueOf(selected)};
return this.getWritableDatabase().query(TABLE_LABELS,
columns,
whereclause,
whereargs,
null,
null,
null
);
}
public Cursor getByRowid(long id) {
String[] columns = new String[]{"rowid AS _id, *"};
return this.getWritableDatabase().query(TABLE_LABELS, columns, "rowid=?", new String[]{String.valueOf(id)},
null, null, null
);
}
}
The following is an example based upon some of the code from the question, that has 3 spinners the 2nd listing values as determined according to what is selected by spinner1. Likewise the 3rd listing values as determined by what is selected by spinner2.
In short each spinner has a manageSprinner? method (? being 1, 2 and 3 respectively).
The manageSpinner? methods retrieve the respective data.
For 2 and 3 the respective data is determined according to the value passed, this value being the selected item from the spinner above it in the hierarchy (i.e. for spinner2 the selected item in spinner1, for spinner3 the selected item in spinner2).
They, the managedSpinner? methods instantiate the adapter if not already instantiated and for Spinners 1 and 2 add the onIstemSelected listener that invokes the managerSpinner? method of the spinner below it in the hierarchy.
If the respective adapter is already instantiated then it swaps the cursor to refresh the data displayed by the spinner.
Note as manageSpinner1 invokes managerSpinner2 and as manageSpinner2 invokes manageSpinner3. There is only the need to invoke manageSpinner1. That is there is always an item that is selected so the onItemSelected method is called from the outset.
The layout for the Activity activity_main.xml :-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<Spinner
android:id="#+id/spinner2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<Spinner
android:id="#+id/spinner3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
The Database helper Databasehandler.java
public class DatabaseHandler extends SQLiteOpenHelper {
// Database Version
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "spinnerExample";
private final Context myContext;
private SQLiteDatabase myDataBase;
// Database Name
// Labels table name
public static final String TABLE_LABELS = "labels"; //<<<< Made public
public static final String TABLE_LABELS1= "labels1";
public static final String TABLE_LABELS2= "labels2";
// Labels Table Columns names
public static final String KEY_ID4 = "input_label";
public static final String KEY_ID12 = "id2"; //<<<< Made public
public static final String KEY_ID = "id";
public static final String KEY_99 = "sno"; //<<<< Made public//<<<< Made public
public static final String KEY_NAME = "name"; //<<<< made public
public static final String KEY_ID1 = "id1"; //<<<< Made public
public static final String KEY_NAME1 = "name1";
public static final String KEY_1 = "number"; //<<<< Made public
public static final String KEY_2 = "outletname"; //<<<< made public
public static final String KEY_3 = "sunday"; //<<<< Made public
public static final String KEY_4 = "monday";
public static final String KEY_5 = "tuesday";
public static final String KEY_6 = "wednesday";
public static final String KEY_7 = "thursday";
public static final String KEY_8 = "saturday";
public static final String KEY_9 = "closed";
public static final String KEY_10 = "calling";
public static final String KEY_11 = "id3";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
myDataBase = this.getWritableDatabase();
this.myContext = context;
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
//boolean dbExist = checkDataBase();
// Category table create query
String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("+ KEY_99 + " INTEGER,"
+ KEY_ID1 + " TEXT," + KEY_ID + " TEXT," + KEY_NAME + " TEXT)";
String CREATE_CATEGORIES_TABLE1 = "CREATE TABLE " + TABLE_LABELS1 + "("
+ KEY_ID1+ " TEXT," + KEY_NAME1+ " TEXT)";
String CREATE_CATEGORIES_TABLE2 = "CREATE TABLE " + TABLE_LABELS2 + "("
+ KEY_11+ " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_1+ " TEXT," + KEY_2+ " TEXT," + KEY_3+ " INTEGER," + KEY_4+ " INTEGER,"+ KEY_5+ " INTEGER," + KEY_6+ " INTEGER," + KEY_7+ " INTEGER," + KEY_8+ " INTEGER," + KEY_9+ " INTEGER," + KEY_10+ " TEXT)";
db.execSQL(CREATE_CATEGORIES_TABLE);
db.execSQL(CREATE_CATEGORIES_TABLE1);
db.execSQL(CREATE_CATEGORIES_TABLE2);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS1);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS2);
// Create tables again
onCreate(db);
}
/**
* Inserting new lable into lables table
* */
public void insertLabel(String message1, String message2,String message3,String message4,String message5,String message6,String message7,String message8,String message9,String message10){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_1, message1);
values.put(KEY_2, message2);
values.put(KEY_10,message10);
values.put(KEY_4,message4);
values.put(KEY_5,message5);
values.put(KEY_6,message6);
values.put(KEY_7,message7);
values.put(KEY_3,message3);
values.put(KEY_9,message9);
values.put(KEY_8,message8);
// Inserting Row
db.insert(TABLE_LABELS2, null, values);
//db.close(); // Closing database connection
}
public void insertLabel1(String label){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME1, label);
db.insert(TABLE_LABELS1, null, values);
//db.close(); // Closing database connection
}
public void insertLabel2(String label){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, label);
db.insert(TABLE_LABELS, null, values);
db.close(); // Closing database connection
}
public Cursor getAllLabelsForSpinner1AsCursor() {
String[] columns = new String[]{"rowid AS _id, *"}; // Need _id column for SimpleCursorAdapter
return this.getWritableDatabase().query(TABLE_LABELS2,columns,null,null,null,null,null);
}
public Cursor getAllLabelsForSpinner2AsCursor(String keyFromSinner1) {
String[] columns = new String[]{"rowid AS _id, *"}; // Need _id column for SimpleCursorAdapter
return this.getWritableDatabase().query(
TABLE_LABELS1,columns,
DatabaseHandler.KEY_NAME1 + " LIKE ?",
new String[]{keyFromSinner1+"%"},
null,null,null
);
}
public Cursor getAllLabelsForSpinner3AsCursor(String keyFromSpinner2) {
String[] columns = new String[]{"rowid AS _id, *"}; // Need _id column for SimpleCursorAdapter
return this.getWritableDatabase().query(
TABLE_LABELS,columns,
DatabaseHandler.KEY_NAME + " LIKE ?",
new String[]{keyFromSpinner2 + "%"},
null,null,null);
}
}
This has had the code not required for the example removed
The Activity MainActivity.java
public class MainActivity extends AppCompatActivity {
DatabaseHandler mDH;
Spinner mSpinner1,mSpinner2,mSpinner3;
Cursor mSpinner1Csr,mSpinner2Csr,mSpinner3Csr;
SimpleCursorAdapter mSpinner1Adapter,mSpinner2Adapter,mSpinner3Adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSpinner1 = this.findViewById(R.id.spinner1);
mSpinner2 = this.findViewById(R.id.spinner2);
mSpinner3 = this.findViewById(R.id.spinner3);
mDH = new DatabaseHandler(this);
addSomeTestingData(); // ADD testing data if none
manageSpinner1(); // Manages spinner1 not that spinner 1 invokes manage spinner2 and spinnr manages spinner3
}
private void addSomeTestingData() {
if(DatabaseUtils.queryNumEntries(mDH.getWritableDatabase(),DatabaseHandler.TABLE_LABELS) > 0) return;
// Data for LABELS2 table (spinner 1 (note 1st column listed in spinner))
mDH.insertLabel("A1","A2","A3","A4","A5","A6","A7","A8","A9","A10");
mDH.insertLabel("B1","B2","B3","B4","B5","B6","B7","B8","B9","B10");
mDH.insertLabel("L1","L2","L3","L4","L5","L6","L7","L8","L9","L10");
// Data for LABELS1 table (spinner 2)
mDH.insertLabel1("A1EXTRA1");
mDH.insertLabel1("A1EXTRA2");
mDH.insertLabel1("B1EXTRA1");
mDH.insertLabel1("B1EXTRA2");
mDH.insertLabel1("L1EXTRA1");
mDH.insertLabel1("L1EXTRA2");
// Data for LABELS table (spinner 3)
mDH.insertLabel2("A1EXTRA1MORE1");
mDH.insertLabel2("A1EXTRA1MORE2");
mDH.insertLabel2("A1EXTRA2MORE1");
mDH.insertLabel2("A1EXTRA2MORE2");
mDH.insertLabel2("B1EXTRA1MORE1");
mDH.insertLabel2("B1EXTRA1MORE2");
mDH.insertLabel2("B1EXTRA2MORE1");
mDH.insertLabel2("B1EXTRA2MORE2");
mDH.insertLabel2("L1EXTRA1MORE1");
mDH.insertLabel2("L1EXTRA1MORE2");
mDH.insertLabel2("L1EXTRA2MORE1");
mDH.insertLabel2("L1EXTRA2MORE2");
}
private void manageSpinner1() {
mSpinner1Csr = mDH.getAllLabelsForSpinner1AsCursor();
if (mSpinner1Adapter == null) {
mSpinner1Adapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_1,
mSpinner1Csr,
new String[]{DatabaseHandler.KEY_1},
new int[]{android.R.id.text1},
0
);
mSpinner1.setAdapter(mSpinner1Adapter);
mSpinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
manageSpinner2(mSpinner1Csr.getString(mSpinner1Csr.getColumnIndex(DatabaseHandler.KEY_1)));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} else {
mSpinner1Adapter.swapCursor(mSpinner1Csr);
}
}
private void manageSpinner2(String keyFromSpinner1) {
mSpinner2Csr = mDH.getAllLabelsForSpinner2AsCursor(keyFromSpinner1);
if (mSpinner2Adapter == null) {
mSpinner2Adapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_1,
mSpinner2Csr,
new String[]{DatabaseHandler.KEY_NAME1},
new int[]{android.R.id.text1},
0
);
mSpinner2.setAdapter(mSpinner2Adapter);
mSpinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
manageSpinner3(mSpinner2Csr.getString(mSpinner2Csr.getColumnIndex(DatabaseHandler.KEY_NAME1)));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} else {
mSpinner2Adapter.swapCursor(mSpinner2Csr);
}
}
private void manageSpinner3(String keyForSpinner3) {
mSpinner3Csr = mDH.getAllLabelsForSpinner3AsCursor(keyForSpinner3);
if (mSpinner3Adapter == null) {
mSpinner3Adapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_1,
mSpinner3Csr,
new String[]{DatabaseHandler.KEY_NAME},
new int[]{android.R.id.text1},
0
);
mSpinner3.setAdapter(mSpinner3Adapter);
} else {
mSpinner3Adapter.swapCursor(mSpinner3Csr);
}
}
}
Note
The above is intended solely as a demonstration of the technique and as such the technique will need to be incorporated and thus that code be adapted as part of that incorporation

Firebase ui 3.1.0 (Firebaselistadapter) No setter/field for mc_name found on class

I've tried my code in normal activity both images and text show. in fragment only image showing but the text is not showing (in both normal and fragment activity I've used same xml layout). I'm using firebaselistadpter for gridview and it works fine. I also tried using it with listview in fragment still images only showing but no text showing. (there is no Error message).
1- my java activity:
public class R_MainCat extends Fragment {
private GridView gridView;
private DatabaseReference myRef;
private FirebaseListAdapter<Sub_Category_Data> adapter;
private TextView mc_name;
private ImageView url;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_gridview, container, false);
rootView.setBackgroundColor(Color.WHITE);
myRef= FirebaseDatabase.getInstance().getReference("Main_Category");
Firebase.getDefaultConfig().setPersistenceEnabled(true);
gridView = (GridView) rootView.findViewById(R.id.gridview);
FirebaseListOptions<Sub_Category_Data> options = new FirebaseListOptions.Builder<Sub_Category_Data>()
.setQuery(myRef, Sub_Category_Data.class).setLayout(R.layout.gridview_icon).build();
adapter = new FirebaseListAdapter<Sub_Category_Data>(options) {
#Override
protected void populateView(View v, Sub_Category_Data model, int position) {
mc_name = v.findViewById(R.id.cat_name);
url = v.findViewById(R.id.img);
mc_name.setText(model.getName());
Picasso.with(getActivity()).load(model.getUrl()).into(url);
}
};
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
switch(i)
{
case 0:
R_DairyProds f1 = new R_DairyProds();
FragmentTransaction fragTransaction1 = getFragmentManager().beginTransaction();
fragTransaction1.replace(R.id.container_view,f1 );
fragTransaction1.addToBackStack(null);
fragTransaction1.commit();
break;
case 1:
R_Bakery f2 = new R_Bakery();
FragmentTransaction fragTransaction2 = getFragmentManager().beginTransaction();
fragTransaction2.replace(R.id.container_view,f2 );
fragTransaction2.addToBackStack(null);
fragTransaction2.commit();
break;
case 2:
R_Grocery f3 = new R_Grocery();
FragmentTransaction fT3 = getFragmentManager().beginTransaction();
fT3.replace(R.id.container_view,f3);
fT3.addToBackStack(null);
fT3.commit();
break;
case 3:
R_FruitsNVegs f4 = new R_FruitsNVegs();
FragmentTransaction fT4 = getFragmentManager().beginTransaction();
fT4.replace(R.id.container_view,f4);
fT4.addToBackStack(null);
fT4.commit();
break;
case 4:
R_CleanNWash f5 = new R_CleanNWash();
FragmentTransaction fT5 = getFragmentManager().beginTransaction();
fT5.replace(R.id.container_view,f5);
fT5.addToBackStack(null);
fT5.commit();
break;
}
}
});
return rootView;
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
}
2-my xml layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
card_view:cardUseCompatPadding="true"
card_view:cardCornerRadius="4dp">
<RelativeLayout
android:descendantFocusability="blocksDescendants"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/img"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"/>
<me.grantland.widget.AutofitLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/img"
>
<TextView
android:id="#+id/cat_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="hello_world"
android:textColor="#000"
android:textSize="20sp"
android:gravity="center"
/>
</me.grantland.widget.AutofitLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
3- my Data model java:
public class Sub_Category_Data {
private String mc_name;
private String url;
public Sub_Category_Data() {
}
public void setName(String mc_name) {
this.mc_name = mc_name;
}
public String getName() {
return mc_name;
}
public void setUrl(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
}
4- snapshot of the output:
text suppose to be showing under the image.
Output in fragment
I want my fragment to show the text data same as what is showing in this image
Output I've tested in normal Activity
5- database snapshot:
Database Image
does anyone have any clue? or have faced this issue before? because I'm lost since there is no error showing besides the fact it works fine in normal activity but text is not showing in the fragment. thank you in advance.
after looking over and over I noticed this in logcat
"No setter/field for mc_name found on class"
I've fixed the problem. It was in the model class getName() and SetName() methods I changed them to same name as the child key name in my firebase you can see picture of the database in the question above. so the new methods are getMc_name() and setMc_name().
public class Sub_Category_Data {
private String mc_name;
private String url;
public Sub_Category_Data() {
}
public String getMc_name() {
return mc_name;
}
public void setMc_name(String mc_name) {
this.mc_name = mc_name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
the output screen shot

FirebaseRecyclerAdapter - populateViewHolder is not populating the data for first time it runs?

FirebaseRecyclerAdapter - populateViewHolder is not populating the data for the first time it runs but when I closed the app and opened it, the data is binded in RecyclerView View Holder.
I am not getting why data is not populating for first time, it is showing blank screen
Here's my MainActivity
mDatabase = FirebaseDatabase.getInstance().getReference();
// [END create_database_reference]
mRecycler = (RecyclerView) findViewById(R.id.recycler_view);
mRecycler.setHasFixedSize(true);
setSupportActionBar(toolbar);
final LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
mRecycler.setLayoutManager(layoutManager);
// Set up FirebaseRecyclerAdapter with the Query
//Query postsQuery = mDatabase.child("EN").child("Courses") ;
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("EN").child("Courses");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Toast.makeText(MainActivity.this, dataSnapshot.toString(), Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(MainActivity.this, databaseError.toString(), Toast.LENGTH_SHORT).show();
}
});
Log.d("ref", String.valueOf(ref));
// Log.d("Query", String.valueOf(postsQuery));
mAdapter = new FirebaseRecyclerAdapter<Course, CourseViewHolder>(Course.class, R.layout.item_home,
CourseViewHolder.class, ref) {
#Override
protected void populateViewHolder(final CourseViewHolder viewHolder, final Course model, final int position) {
viewHolder.bindToPost(model);
}
};
mRecycler.setAdapter(mAdapter);
And the ViewHolder
public class CourseViewHolder extends RecyclerView.ViewHolder {
public TextView titleView;
public TextView descriptionView;
public ImageView IconView;
public TextView lessonCountView;
public CourseViewHolder(View itemView) {
super(itemView);
titleView = (TextView) itemView.findViewById(R.id.title);
descriptionView = (TextView) itemView.findViewById(R.id.description);
//IconView = (ImageView) itemView.findViewById(R.id.star);
}
public void bindToPost(Course post) {
// Log.d("Post", String.valueOf(post));
titleView.setText(post.getName());
descriptionView.setText(post.getDescription());
}
}
My Model Pojo
public class Course {
public String description;
public String title;
public Course() {
// Default constructor required for calls to DataSnapshot.getValue(Post.class)
}
public Course(String title, String description) {
// this.description = author;
this.title = title;
this.description =description;
}
public String getName() {
return title;
}
public String getDescription() {
return description;
}
}
Found the Solution.
The Problem is RecyclerView had a height of wrap_content. So Please make sure your RecyclerView height is set to match_parent. This will fix this issue.
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
If you don't want to use match_parent you shouldn't call mRecycler.setHasFixedSize(true);

How to get a fragment to display after it is called by another fragment (via Activity)

I am at ends wit with my code. I can not get a fragment to display after it is called by another fragment (via Activity). I read the Android Developer guide and many SO's related topic on Fragment/FragmentPagerAdapter/FragmentTransactions and could not resolve my issue. This one would have been an obvious solution Is it possible to remove a fragment without replacing it by another fragment
I have an activity class that will host a fragment based on the tab selected. These fragments are dynamically created by the FragmentPagerAdapter based on user's selection of the tab. In the first tab, it creates FragmentA (ListFragment) which consists of a list of items. When a user clicks on any of the item, it should display another fragment with that item's details but to much of my dismay (and eyes burning), all it does is print out my log in logcat. Please see my code. Perhaps, I am staring at it too long and/or just don't know enough of android to see what's going on. I suspect it has to do with this line: fragTransaction.replace(R.id.curriculumParent, fragC); Now I know this would work if the 1st parameter was a fragment container in the activity's layout file was define but since it is not done statically, I don't know what to put there except for the calling FragmentB's layout file.
Thanks in advance!
MainActivity.java
public class MainActivity extends FragmentActivity implements
FragmentB.OnColorSelectedListener {
private static final String TAG = "MainActivity";
private final Handler handler = new Handler();
private PagerSlidingTabStrip tabs;
private ViewPager pager;
private MyPagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
pager = (ViewPager) findViewById(R.id.pager);
FragmentManager fm = getSupportFragmentManager();
adapter = new MyPagerAdapter(fm);
pager.setAdapter(adapter);
final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4,
getResources().getDisplayMetrics());
pager.setPageMargin(pageMargin);
tabs.setViewPager(pager);
}
...
...
...
public class MyPagerAdapter extends FragmentPagerAdapter {
private final String[] TITLES = { "FragmentB", "2ndTabFragment", "3rdTabFragment" };
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position)
{
return TITLES[position];
}
#Override
public int getCount()
{
return TITLES.length;
}
#Override
public Fragment getItem(int position)
{
Fragment fragment = null;
switch (position) {
case 0:
fragment = Fragment.instantiate(getBaseContext(), FragmentB.class.getName());
break;
case 1:
fragment = Fragment.instantiate(getBaseContext(), SecondTabFragment.class.getName());
break;
case 2:
fragment = Fragment.instantiate(getBaseContext(), ThirdTabFragment.class.getName());
break;
}
return fragment;
}
}
#Override
public void onColorLevelSelected(int position)
{
Log.i(TAG, "Got Here!");
FragmentC fragC = new FragmentC();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction fragTransaction = fm.beginTransaction();
**fragTransaction.replace(R.id.curriculumParent, fragC);**
fragTransaction.addToBackStack(null);
fragTransaction.commit();
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<com.astuetz.PagerSlidingTabStrip
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="48dip"
android:background="#drawable/background_tabs" />
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/tabs"
tools:context=".MainActivity" />
</RelativeLayout>
FragmentB.java
public class FragmentB extends ListFragment{
OnColorSelectedListener mCallback;
private String[] colorLevel = new String[]{
"Yellow",
"Orange",
"Green",
"Blue",
"pink",
"Black"
};
private int[] colorImages = new int[]{
R.drawable.yellow,
R.drawable.orange,
R.drawable.green,
R.drawable.blue,
R.drawable.pink,
R.drawable.black
};
public interface OnColorSelectedListener{
public void onItemLevelSelected(int position);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
List<HashMap<String, String>> colorList = new ArrayList<HashMap<String, String>>();
for(int i = 0; i < 6; i++){
HashMap<String, String> colorMap = new HashMap<String, String>();
colorMap.put("lvl", colorLevel[i]);
colorMap.put("img", Integer.toString(colorImages[i]));
colorList.add(colorMap);
}
String[] from = {"img", "lvl"};
int[] to = {R.id.colorLevelImg, R.id.colorLevelTxt};
SimpleAdapter adapter = new SimpleAdapter(getActivity().getBaseContext(),colorList, R.layout.fragment_b ,from, to);
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
try{
mCallback = (OnColorSelectedListener) activity;
}catch(ClassCastException e){
throw new ClassCastException(activity.toString()
+ " must implement OnColorSelectedListener");
}
}
#Override
public void onListItemClick(ListView l, View v, int pos, long id){
Toast.makeText(getActivity(), "selected color :" + colorLevel[pos],
Toast.LENGTH_LONG).show();
mCallback.onColorLevelSelected(pos);
}
}
fragment_b.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
**android:id="#+id/curriculumParent"**
...
...
android:background="#FEFDFB">
<ImageView
android:id="#+id/colorLevelImg"
...
android:paddingBottom="10dp" />
<LinearLayout
...
android:orientation="vertical" >
<TextView
android:id="#+id/colorLevelTxt"
...
android:textSize="25sp" />
</LinearLayout>
</LinearLayout>
FragmentC.java
public class FragmentC extends Fragment{
public static final String TAG = "Fragment C";
public FragmentC(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
Log.i(TAG, "HI");
return inflater.inflate(R.layout.fragment_c, container, false);
}
}
fragment_c.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFCC00" >
<TextView
android:id="#+id/editText1"
...
android:layout_margin="16dp"
android:text="This is the C Fragment that will replace the B Fragment" >
</TextView>
</RelativeLayout>
I noticed FragmentB.java does not explicitly point to any layout file to inflate. In case you don't know,
ListFragment has a default layout that consists of a single list view
, documented # ListFragment. So you're still fine if you only want a simple ListView, but maybe NOT. But then you have code that references another layout to FragmentB:
new SimpleAdapter(getActivity().getBaseContext(),colorList, R.layout.fragment_b...
Note: R.layout.fragment_b is the layout specified for the ArrayAdapter only! Not for the fragment. But this is normal and may be fine.
In MainActivity, onColorLevelSelected():
fragTransaction.replace(R.id.curriculumParent,...
Note:
I think this replaces the layout only for the adapter and not the fragment.
Perhaps you want to inflate a layout file containing a ListView, and use that for the fragments.
Your problem is basically the layout, work with that.
EDIT:
Code suggestion:
SimpleAdapter adapter = new SimpleAdapter(getActivity().getBaseContext(),colorList, R.layout.fragment_x
public void onColorLevelSelected(int position)
FragmentC fragX = new FragmentX();
...
fragTransaction.replace(R.id.curriculumParent, fragX);
Notes:
Notice I am using an example of an arbitrary FragmentX. The Adapter and the replace() matches each other.
I understand this code change is somewhat considerable. Since I said it, here is a new code suggestion:
public void onListItemClick(ListView l, View v, int pos, long id){
Toast.makeText(getActivity(), "selected color :" + colorLevel[pos], Toast.LENGTH_LONG).show();
SimpleAdapter adapter = new SimpleAdapter(getActivity().getBaseContext(),colorList, R.layout.fragment_b ,from, to);
...
setListAdapter(adapter);
...
mCallback.onColorLevelSelected(pos); }
Note: This code change is made only to be simpler, my attempt. The idea is when the user click on a row in ListView, you know which layout and fragment is used. Hopefully that makes code less complicated.

Resources