Add data in SQLite Database using Fragment in Android - android

I am trying to Add data in SQLite Database using Fragment, but it's not Adding in Database and there is no error while running app.
My code in AddRoom Fragment :
public class AddRoom extends Fragment implements View.OnClickListener {
DatabaseHotel myHotel;
Button bt_addRoom;
EditText ed_roomtype, ed_roomPrice, ed_noOfRoom;
View view;
Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
myHotel = new DatabaseHotel(getActivity());
view = inflater.inflate(R.layout.addroom, container, false);
bt_addRoom = (Button)view.findViewById(R.id.bt_addroom);
ed_roomtype = (EditText)view.findViewById(R.id.ed_roomtype);
ed_roomPrice = (EditText)view.findViewById(R.id.ed_roomprice);
ed_noOfRoom = (EditText)view.findViewById(R.id.ed_noofrooms);
return view;
}
#Override
public void onClick(View v) {
bt_addRoom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addRoom();
}
});
}
private void addRoom(){
String roomType = ed_roomtype.getText().toString();
int roomPrice = Integer.parseInt(ed_roomPrice.getText().toString());
int noOfRoom = Integer.parseInt(ed_noOfRoom.getText().toString());
boolean inserted = myHotel.addRoom(roomType, roomPrice, noOfRoom);
if (inserted){
Message.message(context, "Room Added Succeccfully");
}else {
Message.message(context, "Room Not Added!!");
}
}
}
In My Database class : addRoom() method code:
public boolean addRoom(String roomType, int roomPrice, int numberOfRoom){
SQLiteDatabase db = mydb.getReadableDatabase();
ContentValues cv = new ContentValues();
cv.put(Database.ROOM_TYPE, roomType);
cv.put(Database.ROOM_PRICE, roomPrice);
cv.put(Database.NUMBER_OF_ROOMS, numberOfRoom);
try {
long result = db.insert(Database.ROOM_TABLE,null, cv);
if (result == -1){
return false;
}else {
return true;
}
}catch (SQLException e){
Message.message(context, e+"");
}
return true;
}

I think you missed
bt_addRoom.setOnClickListener(this);
in onCreateView(..). You should register OnClickListener first.

What MD said... but you might also want mydb.getWriteableDatabase(); and not getReadableDatabase() as well

Related

IndexOutOfBoundException while reading from Cursor

I'm trying to use a CursorLoader but keep getting an IndexOutOfBounds error when reading from the Cursor. Relevant error lines from Logcat:
at com.codephillip.app.busticket.SelectRouteFragment.onLoadFinished(SelectRouteFragment.java:96)
at com.codephillip.app.busticket.SelectRouteFragment.onLoadFinished(SelectRouteFragment.java:28)
This is the fragment class:
public class SelectRouteFragment extends Fragment implements MaterialSpinner.OnItemSelectedListener, LoaderManager.LoaderCallbacks {
private static final String TAG = SelectRouteFragment.class.getSimpleName();
private MaterialSpinner destSpinner;
private MaterialSpinner sourceSpinner;
private Button selectButton;
private String destination;
private String source;
public SelectRouteFragment() {
}
public static SelectRouteFragment newInstance() {
return new SelectRouteFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_select_route, container, false);
destSpinner = rootView.findViewById(R.id.dest_spinner);
sourceSpinner = rootView.findViewById(R.id.source_spinner);
destSpinner.setOnItemSelectedListener(this);
sourceSpinner.setOnItemSelectedListener(this);
selectButton = rootView.findViewById(R.id.select_button);
selectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (source.equals(destination)) {
Toast.makeText(getContext(), "Choose a different Destination", Toast.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(getContext(), BookActivity.class);
intent.putExtra(Utils.SOURCE, source);
intent.putExtra(Utils.DESTINATION, destination);
getActivity().startActivity(intent);
}
}
});
return rootView;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getLoaderManager().initLoader(2, null, this);
}
#Override
public Loader onCreateLoader(int id, Bundle args) {
return new CursorLoader(getContext(), LocationsColumns.CONTENT_URI, null, null, null, null);
}
#Override
public void onLoadFinished(Loader loader, Cursor data) {
Log.d(TAG, "onLoadFinished: started");
LocationsCursor cursor = new LocationsCursor(data);
List locations = new ArrayList<>();
if (cursor.moveToFirst()) {
do {
locations.add(cursor.getName());
} while (cursor.moveToNext());
}
// Set default route values
source = locations.get(0);
destination = locations.get(0);
ArrayAdapter dataAdapter = new ArrayAdapter(getContext(), android.R.layout.simple_expandable_list_item_1, locations);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sourceSpinner.setAdapter(dataAdapter);
destSpinner.setAdapter(dataAdapter);
}
#Override
public void onLoaderReset(Loader loader) {
}
#Override
public void onItemSelected(MaterialSpinner view, int position, long id, Object itemObject) {
Snackbar.make(view, "Clicked " + itemObject.toString(), Snackbar.LENGTH_LONG).show();
String item = itemObject.toString();
Log.d(TAG, "onItemSelected: " + item);
if (view.getId() == destSpinner.getId()) {
Log.d(TAG, "onItemSelected: clicked dest");
destination = item;
} else {
Log.d(TAG, "onItemSelected: clicked source");
source = item;
}
}
}
Any help understanding the issue would be greatly appreciated.
I guess the issue is happening here:
source = locations.get(0);
destination = locations.get(0);
If cursor is empty, locations will also be empty and then, locations.get(0) will throw an exception.
You should check if location is not empty.
if(locations.size() > 0) {
...
}

SearchView doesn't work with RecyclerView & SQLite

I have a Fragment with a RecyclerView. users input data and they will store in a SQLite DataBase. i am trying to Search in the items of this RecyclerView but it does not work,
here is my Fragment :
public class FragmentOne extends Fragment {
private RecyclerView mDetailRecyclerView;
private DetailAdapter mAdapter;
private boolean mNumberVisible;
private SearchView sv;
private ArrayList<Detail> mDetails=new ArrayList<>();
private View view;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_one_layout,
container, false);
mDetailRecyclerView = (RecyclerView) view.findViewById(R.id.detail_recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
layoutManager.setReverseLayout(true); //This will reverse the data order but not scroll the RecyclerView to the last item
layoutManager.setStackFromEnd(true); //For keeping data order same and simply scrolling the RecyclerView to the last item
mDetailRecyclerView.setLayoutManager(layoutManager);
if (savedInstanceState != null) {
mNumberVisible =
savedInstanceState.getBoolean(SAVED_NUMBER_VISIBLE);
}
sv = (SearchView) view.findViewById(R.id.sv);
mAdapter = new DetailAdapter(mDetails);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit (String query) {
return false;
}
#Override
public boolean onQueryTextChange(String query) {
getDetailsSearch(query);
return false;
}
});
initViews();
updateUI();
return view;
}
#Override
public void onResume() {
super.onResume();
updateUI();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(SAVED_NUMBER_VISIBLE, mNumberVisible);
}
..
..
private class DetailHolder extends RecyclerView.ViewHolder
implements View.OnClickListener, View.OnLongClickListener {
private TextView mTitleTextView;
// private TextView mDateTextView;
private Detail mDetail;
private RatingBar mRatingBar;
public DetailHolder(LayoutInflater inflater, ViewGroup parent) {
super(inflater.inflate(R.layout.list_item_detail,
parent, false));
itemView.setOnClickListener(this);
itemView.setOnLongClickListener(this);
mTitleTextView = (TextView) itemView.findViewById(R.id.detail_title);
mRatingBar = (RatingBar) itemView.findViewById(R.id.ratingBar);
}
public void bind(Detail detail) {
mDetail = detail;
mTitleTextView.setText(mDetail.getTitle());
mRatingBar.setRating(mDetail.getRate());
}
#Override
public void onClick(View view) {
Intent intent = DetailPagerActivity.newIntent(getActivity(),
mDetail.getId());
startActivity(intent);
}
}
private class DetailAdapter extends RecyclerView.Adapter<DetailHolder> {
private List<Detail> mDetails;
private Detail mDetail;
public DetailAdapter(List<Detail> details) {
mDetails = details;
}
#Override
public DetailHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
return new DetailHolder(layoutInflater, parent);
}
#Override
public void onBindViewHolder(DetailHolder holder, int position) {
Detail detail = mDetails.get(position);
holder.bind(detail);
}
#Override
public int getItemCount() {
return mDetails.size();
}
public void setDetails(final List<Detail> details) {
mDetails = details;
}
..
..
}
public void initViews(){
mDetailRecyclerView.setAdapter(mAdapter);
initSwipe();
}
..
..
private void getDetailsSearch (String searchTerm) {
mDetails.clear();
DBAdapter db = new DBAdapter(getActivity());
db.openDB();
Detail p = null;
Cursor c = db.retrieve(searchTerm);
while (c.moveToNext()) {
String title = c.getString(2);
p = new Detail();
p.setTitle(title);
mDetails.add(p);
}
db.closeDB();
mDetailRecyclerView.setAdapter(mAdapter);
}
}
and this is my Database Adapter:
public class DBAdapter {
Context c;
SQLiteDatabase db;
DetailBaseHelper helper;
public DBAdapter (Context c) {
this.c = c;
helper = new DetailBaseHelper(c);
}
public void openDB() {
try {
db = helper.getWritableDatabase();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void closeDB() {
try {
helper.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public Cursor retrieve (String searchTerm) {
String[] columns = {
"_id",
"uuid",
"title",
"des",
"date",
"rate"
Cursor c = null;
if (searchTerm != null && searchTerm.length()>0) {
String sql ="SELECT * FROM " +DetailDbSchema.DetailTable.NAME+
" WHERE "+DetailDbSchema.DetailTable.Cols.TITLE+
" LIKE '%"+searchTerm+"%'";
c = db.rawQuery(sql, null);
return c;
}
c = db.query(DetailDbSchema.DetailTable.NAME, columns,
null, null, null, null, null);
return c;
}
}
and here is DataBase Helper:
public class DetailBaseHelper extends SQLiteOpenHelper{
private static final int VERSION = 1;
private static final String DATABASE_NAME = "detailBase.db";
public DetailBaseHelper (Context context) {
super(context, DATABASE_NAME, null, VERSION);
}
#Override
public void onCreate (SQLiteDatabase db) {
db.execSQL("create table " + DetailTable.NAME +
"(" +
" _id integer primary key autoincrement," +
DetailTable.Cols.UUID + ", " +
DetailTable.Cols.TITLE + ", " +
DetailTable.Cols.DES + ", " +
DetailTable.Cols.DATE + ", " +
DetailTable.Cols.RATE +
")"
);
}
#Override
public void onUpgrade (SQLiteDatabase db,
int oldVersion, int newVersion) {
}
}
here is the tutorial that i used for this,
I'll be appreciate if u have any idea for helping me.
I think that the main problem is here you're changing the adapter, but the new adapter was never modified by the data of the results, and also you have to notify your recycler that the data set changed. so
private void getDetailsSearch (String searchTerm) {
mDetails.clear();
/// the loop wiith the cursor
/// change the dataset
mAdapter = new DetailAdapter(mDetails);
mDetailRecyclerView.setAdapter(mAdapter);
/// tell the recycler there is a different data to display
mDetailRecyclerView.notifyDataSetChanged();
}

Attempting to access a closed CursorWindow.Most probable cause: cursor is deactivated prior to calling this method

How to resolve given error? It happens when I try to refresh cursor from actionbar and sometimes when I try to delete again after long click on list item.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private final String QUERY_SELECTALL = "SELECT * FROM " + RjecnikDB.TABLE;
private RjecnikCursorAdapter adapter;
private RjecnikDB dbRjecnik;
private SQLiteDatabase db;
private Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onRestart() {
super.onRestart();
refresh();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.search_bar) {
return true;
} else if (id == R.id.refresh) {
refresh();
}
return super.onOptionsItemSelected(item);
}
public void refresh() {
dbRjecnik = RjecnikDB.getInstance(this);
db = dbRjecnik.getReadableDatabase();
cursor = db.rawQuery(QUERY_SELECTALL, null);
adapter = RjecnikCursorAdapter.getInstance(this, cursor);
adapter.changeCursor(cursor);
}
WordsListFragment.java
public class WordsListFragment extends Fragment {
private final String QUERY_SELECTALL = "SELECT * FROM " + RjecnikDB.TABLE;
private RjecnikCursorAdapter adapter;
private RjecnikDB dbRjecnik;
private SQLiteDatabase db;
private Cursor cursor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.words_list_fragment_layout, container, false);
ListView listView = (ListView) view.findViewById(R.id.listView);
fabAddWord = (FloatingActionButton) view.findViewById(R.id.fabAddWord);
dbRjecnik = RjecnikDB.getInstance(getActivity());
db = dbRjecnik.getWritableDatabase();
cursor = db.rawQuery(QUERY_SELECTALL, null);
adapter = RjecnikCursorAdapter.getInstance(getActivity(), cursor);
listView.setAdapter(adapter);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
int _id = cursor.getInt(cursor.getColumnIndex(RjecnikDB.COLUMN_ID));
DiscardDialogFragment newFragment = new DiscardDialogFragment(_id);
newFragment.show(getFragmentManager(), "discard");
return true;
}
});
return view;
}
public void changeCursor() {
dbRjecnik = RjecnikDB.getInstance(getActivity());
db = dbRjecnik.getReadableDatabase();
cursor = db.rawQuery(QUERY_SELECTALL, null);
adapter.changeCursor(cursor);
}
public void deleteOnLongClick(int id) {
db = dbRjecnik.getWritableDatabase();
db.delete(RjecnikDB.TABLE, RjecnikDB.COLUMN_ID + " = ?", new String[] { Integer.toString(id) } );
}
public class DiscardDialogFragment extends DialogFragment {
int colID;
DiscardDialogFragment() {}
DiscardDialogFragment(int colID) { this.colID = colID; }
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Izbriši riječ?")
.setPositiveButton("IZBRIŠI",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
deleteOnLongClick(colID);
changeCursor();
Toast.makeText(getActivity(),
"Riječ je izbrisana iz baze", Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("OTKAŽI", null);
return builder.create();
}
}
Does anyone have an idea to grasp this changeCursor or refresh in one class, I tried many ways, but always it was errors.
I was experiencing this same error when returning to my app (from another app, which my app opened).
The solution for me was to replace my spinnerAdapter.changeCursor(cursor) code with spinnerAdapter.swapCursor(cursor).
I suspect that we both had similar issues. I had a listener on a CheckBox in each list item. The listener was firing while the cursor was closing. Post your code for RjecnikCursorAdapter or you can test the listeners yourself. Check the listeners set in the code above or any set in RjecnikCursorAdapter.bindView or RjecnikCursorAdapter.getView.
This comment is incorrect:
I have not any cursor.close() call.
adapter.changeCursor(cursor) closes the old cursor for you.
I had same problem in my case clean and rebuild the project worked for me .
In addition i even deleted the app data in my mobile and changing the
adapter.close() to adapter.swapCursor(cursor);

How to put values from a textview in a row of a listview to a fragment

Working on android app' and I want to pass value from my textview that is in a row of a listview and put it in a fragment. I hear about convertView.gettag and settag method put I don't know how to deal with.
My code:
public class EvaluationsFragment extends CustomFragment implements View.OnClickListener, AdapterView.OnItemSelectedListener {
private Patient mPatient;
private View myView;
private Context context;
private Button btnAjoutEvaluation;
private ListView evaluations_historic_liste;
private List<Evaluation>mEvaluation;
private EvaluationDto mEvaluationDto;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState){
myView = inflater.inflate(R.layout.fragment_evaluations, container,false);
return myView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
init();
}
private void init(){
evaluations_historic_liste = (ListView)myView.findViewById(R.id.evaluations_historic_liste);
btnAjoutEvaluation = (Button)myView.findViewById(R.id.evaluations_add__btn);
btnAjoutEvaluation.setOnClickListener(this);
TypeEvaluation mNouveauTypeEvaluation;
mPatient =((DossierActivity)mRootActivity).mPatient;
mEvaluationDto = new EvaluationDto(mRootActivity.getApplicationContext());
evaluations_historic_liste.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
EvaluationAdapter.EvaluationItem item = (EvaluationAdapter.EvaluationItem)view.getTag();
openDetailEvaluation(item);
}
});
mEvaluationDto.open();
try{
mEvaluation = mEvaluationDto.getEvaluationsByPatientId(mPatient.getId());
}catch (SQLException e) {
Log.e(Constants.APP_LOG_TAG, e.getMessage());
ACRA.getErrorReporter().handleException(e);
} finally{
mEvaluationDto.close();
}
if(mEvaluation != null && mEvaluation.size() >0){
evaluations_historic_liste.setAdapter(new EvaluationAdapter(mRootActivity,mEvaluation));
}else {
evaluations_historic_liste.setVisibility(View.GONE);
}
}
#Override
public void onClick(View v) {
switch(v.getId()){
case (R.id.evaluations_add__btn):
openNewEvaluation();
break;
}
}
public void openNewEvaluation(){
Fragment fragment = new EvaluationNouvelleFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.content_frame, new EvaluationNouvelleFragment());
fragmentTransaction.commit();
}
public void openDetailEvaluation(EvaluationAdapter.EvaluationItem item){
EvaluationAdapter evaluationAdapter = new EvaluationAdapter();
EvaluationDetailHistoriqueFragment detail = new EvaluationDetailHistoriqueFragment();
Bundle args = new Bundle();
args.putString(EvaluationDetailHistoriqueFragment.DATA_RECEIVE, /*HERE I NEED TO PUT item_evaluation_nom.setText()*/ );
detail.setArguments(args);
getFragmentManager().beginTransaction().replace(R.id.content_frame, detail).commit();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public class EvaluationAdapter extends BaseAdapter {
private Context mcontext;
private List<EvaluationItem> mItems = new ArrayList<EvaluationItem>();
public EvaluationAdapter(){}
public EvaluationAdapter(Context context, List<Evaluation> values) {
this.mcontext = context;
for (Evaluation e : values) {
mItems.add(new EvaluationItem(e));
}
}
#Override
public int getCount() {
return mItems.size();
}
#Override
public EvaluationItem getItem(int position) {
return mItems.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
EvaluationItemHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(mcontext).inflate(R.layout.list_items_historic_evaluations, parent, false);
holder = new EvaluationItemHolder();
holder.item_evaluation_date = (TextView) convertView.findViewById(R.id.item_evaluation_date);
holder.item_evaluation_nom = (TextView) convertView.findViewById(R.id.item_evaluation_nom);
holder.item_evaluation_personnel = (TextView) convertView.findViewById(R.id.item_evaluation_personnel);
holder.item_evaluation_score = (TextView) convertView.findViewById(R.id.item_evaluation_score);
holder.item_evaluation_date_reevaluation = (TextView) convertView.findViewById(R.id.item_evaluation_date_reevaluation);
convertView.setTag(holder);
}else{
holder = (EvaluationItemHolder)convertView.getTag();
}
final EvaluationItem item = getItem(position);
int score = (item.getScoreTV()).intValue();
holder.item_evaluation_date.setText( + " " + item.getDateTV());
holder.item_evaluation_nom.setText(item.getTypeEvalTV());
if (item.getPersonnelTV() != null) {
holder.item_evaluation_personnel.setText( + " " + item.getPersonnelTV());
}
holder.item_evaluation_score.setText( + String.valueOf(score));
if (item.getDateReevalTV() != null) {
holder.item_evaluation_date_reevaluation.setText( item.getDateReevalTV());
}
// convertView.setTag(1,item.getTypeEvalTV());
return convertView;
}
public class EvaluationItem {
private String dateTV;
private String typeEvalTV;
private String personnelTV;
private Double scoreTV;
private String dateReevalTV;
public String getDateTV() {return dateTV;}
public void setDateTV(String dateTV) {
this.dateTV = dateTV;
}
public String getTypeEvalTV() {
return typeEvalTV;
}
public void setTypeEvalTV(String typeEvalTV) {
this.typeEvalTV = typeEvalTV;
}
public String getPersonnelTV() {
return personnelTV;
}
public void setPersonnelTV(String personnelTV) {
this.personnelTV = personnelTV;
}
public Double getScoreTV() {
return scoreTV;
}
public void setScoreTV(Double scoreTV) {
this.scoreTV = scoreTV;
}
public String getDateReevalTV() {
return dateReevalTV;
}
public void setDateReevalTV(String dateReevalTV) {
this.dateReevalTV = dateReevalTV;
}
public EvaluationItem(Evaluation e){
this.dateTV = e.getDate();
this.typeEvalTV = e.getTypeEvaluation().getLibelle();
this.personnelTV = e.getPersonnelLibelle();
this.scoreTV = e.getScore();
this.dateReevalTV = e.getDateReevaluation();
}
}
}
public static class EvaluationItemHolder{
public TextView item_evaluation_date;
public TextView item_evaluation_nom;
public TextView item_evaluation_personnel;
public TextView item_evaluation_score;
public TextView item_evaluation_date_reevaluation;
}
}
You were doing good, you need a Bundle to do this.
First of all create a String where you can keep the value of
holder.item_evaluation_nom.getText();
Then for example you do this :
String itemEvaluation = holder.item_evaluation_nom.getText();
This is the correct Bundle
EvaluationDetailHistoriqueFragment detail = new EvaluationDetailHistoriqueFragment();
Bundle bundle = new Bundle();
bundle.putString("text", itemEvaluation);
detail.setArguments(bundle);
Then to retrieve this you do this :
Bundle bundle = this.getArguments();
if (bundle != null) {
String itemEvaluation = bundle.getString("text", "");
}
hope it helps.
EDIT
You'll need to add an Adapter to your evaluations_historic_liste list.
You can do this doing :
evaluations_historic_liste.setAdapter(new EvaluationAdapter(getActivity(),mEvaluation));
mEvaluation is the List that you have to put data on it.
Then in your ListView add this :
evaluation_historic_liste.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id){
String itemEvaluation = (String) ((TextView)view.findViewById(R.id.item_evaluation_nom)).getText();
//or
String itemEvaluation=(evaluation_historic_liste.getItemAtPosition(position).toString());
}
}

ListView disappears when returning to activity after clicking Up button

I'm using Parse.com to populate a ListView in the second activity of my app. Clicking on an item in the ListView opens up a third activity. The problem is that when using the Up button to return to the second activity the ListView is gone. For some reason this behavior does not occur when the Back button is used. Also, it does not occur when just using a normal query in the 2nd activity. Something about the query.whereEqualsTo("department", department) line is throwing the whole thing off.
1st Activity:
public class MainActivity extends ActionBarActivity {
private Button mMEButton;
private Button mCEButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMEButton = (Button)findViewById(R.id.meButton);
mCEButton = (Button)findViewById(R.id.ceButton);
mMEButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ProfessorsActivity.class);
intent.putExtra("department", "ME");
startActivity(intent);
}
});
mCEButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ProfessorsActivity.class);
intent.putExtra("department", "CE");
startActivity(intent);
}
});
}
2nd Activity:
public class ProfessorsActivity extends ActionBarActivity {
private ParseQueryAdapter<ParseObject> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_professors);
Intent intent = getIntent();
final String department = intent.getStringExtra("department");
ParseQueryAdapter.QueryFactory<ParseObject> factory =
new ParseQueryAdapter.QueryFactory<ParseObject>() {
public ParseQuery create() {
ParseQuery query = new ParseQuery("Professor");
query.whereEqualTo("department", department);
return query;
}
};
adapter = new ParseQueryAdapter<ParseObject>(this, factory) {
#Override
public View getItemView(ParseObject professor, View v, ViewGroup parent) {
if (v == null) {
v = View.inflate(getContext(), R.layout.professor_item, null);
}
TextView contentView = (TextView) v.findViewById(R.id.professorNameTextView);
contentView.setText(professor.getString("lastName") + ", " + professor.getString("firstName"));
return v;
}
};
//adapter.setTextKey("lastName");
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final ParseObject tappedProfessor = adapter.getItem(position);
String professorId = tappedProfessor.getObjectId();
Intent intent = new Intent(ProfessorsActivity.this, OfficeHoursActivity.class);
intent.putExtra("professorId", professorId);
startActivity(intent);
}
});
}
3rd Activity:
public class OfficeHoursActivity extends ActionBarActivity {
private TextView mNameTextView;
private TextView mTimeTextView1;
private TextView mDaysTextView1;
private TextView mTimeTextView2;
private TextView mDaysTextView2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_office_hours);
Intent intent = getIntent();
String professorId = intent.getStringExtra("professorId");
mNameTextView = (TextView) findViewById(R.id.professorName);
mTimeTextView1 = (TextView) findViewById(R.id.officeHourTime1);
mDaysTextView1 = (TextView) findViewById(R.id.officeHourDays1);
mTimeTextView2 = (TextView) findViewById(R.id.officeHourTime2);
mDaysTextView2 = (TextView) findViewById(R.id.officeHourDays2);
mNameTextView.setVisibility(INVISIBLE);
mTimeTextView1.setVisibility(INVISIBLE);
mDaysTextView1.setVisibility(INVISIBLE);
mTimeTextView2.setVisibility(INVISIBLE);
mDaysTextView2.setVisibility(INVISIBLE);
ParseQuery<ParseObject> query = ParseQuery.getQuery("Professor");
// Retrieve the object by id
query.getInBackground(professorId, new GetCallback<ParseObject>() {
public void done(ParseObject currentProfessor, ParseException e) {
if (e == null) {
mNameTextView.setText(currentProfessor.getString("lastName") + ", " + currentProfessor.getString("firstName"));
mTimeTextView1.setText(currentProfessor.getString("start1") + " - " + currentProfessor.getString("end1"));
mDaysTextView1.setText(currentProfessor.getString("days1"));
mNameTextView.setVisibility(VISIBLE);
mTimeTextView1.setVisibility(VISIBLE);
mDaysTextView1.setVisibility(VISIBLE);
if (currentProfessor.getString("start2") != null) {
mTimeTextView2.setText(currentProfessor.getString("start2") + " - " + currentProfessor.getString("end2"));
mDaysTextView2.setText(currentProfessor.getString("days2"));
mTimeTextView2.setVisibility(VISIBLE);
mDaysTextView2.setVisibility(VISIBLE);
}
} else {
//something went wrong
}
}
});
The up button creates a new instance of the parent activity by default.
If you want it to behave as the back button just override "onOptionsItemSelected" in "OfficeHoursActivity" and do the following:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == android.R.id.home) {
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
private void ListView(){
ParseQueryAdapter.QueryFactory<ParseObject> factory =
new ParseQueryAdapter.QueryFactory<ParseObject>() {
public ParseQuery create() {
ParseQuery query = new ParseQuery("Professor");
query.whereEqualTo("department", department);
return query;
}
};
adapter = new ParseQueryAdapter<ParseObject>(this, factory) {
#Override
public View getItemView(ParseObject professor, View v, ViewGroup parent) {
if (v == null) {
v = View.inflate(getContext(), R.layout.professor_item, null);
}
TextView contentView = (TextView) v.findViewById(R.id.professorNameTextView);
contentView.setText(professor.getString("lastName") + ", " + professor.getString("firstName"));
return v;
}
};
//adapter.setTextKey("lastName");
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
}
Now call this method from onResume(). Don't call it from onCreate().
#Override
public void onResume(){
super.onResume();
ListView();
}
Now check.. May be you problem will solved..!!!
I solved this problem by adding the following tag to the second activity within the AndroidManifest.xml file.
android:launchMode="singleTop"
This prevents the Up button from recreating the activity when it is clicked.

Categories

Resources