Creating the 'next' button based on another activity - java

I am making a drawing app. I have two files : 'CatList_Activity.java' and 'Draw_Activity.java'. CatList_Activity is the page with the menu where all the images are displayed, and by clicking on one (method 'onItemClick') it sends me to the page Draw_Activity and displays that image, id being the attribute 'position' in the override method. What I want to do is to create the 'next' button (via imageView with onClickListener) in Draw_Activity, which will straight away send me to the next image. My guess would be to somehow increment 'position' value in CatList_Activity file, but I am not sure how to do it
CatList_Activity.java
public class CatList_Activity extends ActionBarActivity {
GridView grid;
private String[] arrImagesStrings;
String Foldername;
CatListAdapter adapter;
private AdView mAdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.catlist_activity);
Toolbar toolbar = (android.support.v7.widget.Toolbar)
this.findViewById(R.id.toolbar);
toolbar.setTitle("");
this.setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
mAdView = (AdView) findViewById(R.id.adView);
mAdView.loadAd(new AdRequest.Builder().build());
grid = (GridView) findViewById(R.id.lsv_catlist);
Intent i = getIntent();
Foldername = i.getStringExtra("Folder");
arrImagesStrings = listAssetFiles(Foldername);
adapter = new CatListAdapter(CatList_Activity.this, R.layout.catlist_item, arrImagesStrings, Foldername);
grid.setAdapter(adapter);
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
//Toast.makeText(getApplicationContext(), ""+selectedImagePath, Toast.LENGTH_SHORT).show();
//Log.e("name", ""+Foldername+"/"+arrImagesStrings[position]);
Intent intentdraw = new Intent(getApplicationContext(), Draw_Activity.class);
intentdraw.putExtra("Folder", Foldername + "/" + arrImagesStrings[position]);
startActivity(intentdraw);
}
}
}
}
Draw_Activity.java
public class Draw_Activity extends Activity {
private PaintView pv;
protected View layout;
protected int progress;
protected Dialog dialog;
protected Dialog textdialog;
private String[] arrImagesStrings;
protected float stroke = 6;
int postion;
private String fileName;
private int ColorAh = Color.BLACK;
String Foldername;
RelativeLayout re;
private AdView mAdView;
ImageView img_next;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.drawpic_activity);
mAdView = (AdView) findViewById(R.id.adView);
mAdView.loadAd(new AdRequest.Builder().build());
re = (RelativeLayout) findViewById(R.id.rell);
img_next = (ImageView) findViewById(R.id.image_next);
this.fileName = null;
super.onCreate(savedInstanceState);
this.pv = new PaintView(this);
re.addView(pv);
//setContentView(this.pv);
this.pv.togglePencil(true);
Intent i = getIntent();
Foldername = i.getStringExtra("Folder");
img_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
???
}
});
}
}

In your CatList_Activity, change
Intent intentdraw=new Intent(getApplicationContext(),Draw_Activity.class);
intentdraw.putExtra("Folder", Foldername+"/"+arrImagesStrings[position]);
to
Intent intentdraw=new Intent(getApplicationContext(),Draw_Activity.class);
intentdraw.putExtra("FolderName", Foldername);
intentdraw.putExtra("position", position);
intentdraw.putExtra("images", arrImagesStrings);
In your Draw_Activity, handle onClick to increment the position and get the desired path.
Foldername=i.getStringExtra("FolderName");
position = i.getIntExtra("position", 0);
images = i.getStringArrayExtra("images");
path = Foldername + "/" + images[position];

Make list of images .... Do something like this
mDrawerList = (ListView) findViewById(R.id.slider_list);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < menutitles.length; i++) {
RowItem items = new RowItem(menutitles[i], menuIcons.getResourceId(

Related

How can I hide some content from showing to recyclerview

I am working on code which I copied from somewhere as a learner. The app displays data in recyclerview, this data is coming from firebase database. All is working well, the data is displaying nicely in recyclerview.
My worry now is: i have added another recyclerview in the same activity. So now I have two recyclerviews with these IDs: recyclerview and recyclerview2. They are in one activity but in different layouts, and only one layout is visible at a time, and by clicking the button it hides one layout and shows another. For now the recyclerviews are showing same data.
What i want now is this: In these recyclerviews I have a TextView which changes text time by time. It sometimes shows this text 'CLOSED'. So i want all the data which has a textview which shows 'CLOSED' to be shown on recyclerview2 and will be unavailable on the first recyclerview.
So my issue is to make the data not to display on recyclerview (first one) if the textview is showing 'CLOSED' and i want the recyclerview2 to show only data which has a textview showing this text 'CLOSED'
I do not know where to start from. Below is my MainActivity.java where i want the code to be added.
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView, recyclerView2;
private DatabaseReference mDatabase, vDatabase;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
TextView rtrratio, rtrratiopercentage, tppipss, slpipss, commenting, entry, tp, sl, tv1, tv2, tv3;
RelativeLayout rSignals, rCalendar, rLessons, rServices, rContact;
ImageButton imsignals, imcalendar, imlessons, imservices, imcontact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
//defining main buttons (Image buttons)
imsignals = (ImageButton) findViewById(R.id.im_signals_id);
imcalendar = (ImageButton) findViewById(R.id.im_calendar_id);
imlessons = (ImageButton) findViewById(R.id.im_lessons_id);
imservices = (ImageButton) findViewById(R.id.im_services_id);
imcontact = (ImageButton) findViewById(R.id.im_contact_id);
//defining textviews
entry = (TextView) findViewById(R.id.entry);
tppipss = (TextView) findViewById(R.id.tpp);
slpipss = (TextView) findViewById(R.id.slp);
rtrratio = (TextView) findViewById(R.id.riskreward);
rtrratiopercentage = (TextView) findViewById(R.id.rrewardp);
commenting = (TextView) findViewById(R.id.comment);
tp = (TextView) findViewById(R.id.tp);
sl = (TextView) findViewById(R.id.sl);
//bottom navigation
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
//button definitions
Button btnRunning = (Button) findViewById(R.id.sRunning);
Button btnPending = (Button) findViewById(R.id.sPending);
Button btnClosed = (Button) findViewById(R.id.sClosed);
//layouts definitions for bottom navigation
rSignals = (RelativeLayout) findViewById(R.id.rlsignals);
rCalendar = (RelativeLayout) findViewById(R.id.rlcalendar);
rLessons = (RelativeLayout) findViewById(R.id.rllessons);
rServices = (RelativeLayout) findViewById(R.id.rlservices);
rContact = (RelativeLayout) findViewById(R.id.rlcontact);
//layouts definitions for signals layout
final RelativeLayout rRunning = (RelativeLayout) findViewById(R.id.rlRunning);
final LinearLayout rPending = (LinearLayout) findViewById(R.id.rlHistory);
final LinearLayout rClosed = (LinearLayout) findViewById(R.id.rlRating);
//initialize recyclerview and FIrebase objects
//for running signals
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
//for closed signals
recyclerView2 = (RecyclerView) findViewById(R.id.recyclerview2);
recyclerView2.setLayoutManager(new LinearLayoutManager(this));
recyclerView2.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
//for running signals
recyclerView.setLayoutManager(linearLayoutManager);
//for closed signals
recyclerView.setLayoutManager(linearLayoutManager);
//for signals get child as Blogzone
mDatabase = FirebaseDatabase.getInstance().getReference().child("Blogzone");
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (mAuth.getCurrentUser() == null) {
Intent loginIntent = new Intent(MainActivity.this, RegisterActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
}
}
};
/////////////////////////////////////////////////////////////////////////////////////////////
//signals
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
FirebaseRecyclerAdapter<Blogzone, BlogzoneViewHolder> FBRA = new FirebaseRecyclerAdapter<Blogzone, BlogzoneViewHolder>(
Blogzone.class,
R.layout.card_items,
BlogzoneViewHolder.class,
mDatabase
) {
#Override
protected void populateViewHolder(BlogzoneViewHolder viewHolder, Blogzone model, int position) {
final String post_key = getRef(position).getKey().toString();
viewHolder.setPair(model.getPair());
viewHolder.setBuySell(model.getBuysell());
viewHolder.setOpenPrice(model.getOpenprice());
viewHolder.setTakeProfit(model.getTakeprofit());
viewHolder.setStopLoss(model.getStoploss());
viewHolder.setProfitPips(model.getProfitpips());
viewHolder.setLossPips(model.getLosspips());
viewHolder.setComment(model.getComment());
viewHolder.setResult(model.getResult());
viewHolder.setRewarding(model.getRewarding());
viewHolder.setRewardingP(model.getRewardingP());
//viewHolder.setImageUrl(getApplicationContext(), model.getImageUrl());
//viewHolder.setUserName(model.getUsername());
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Intent singleActivity = new Intent(MainActivity.this, SinglePostActivity.class);
// singleActivity.putExtra("PostID", post_key);
// startActivity(singleActivity);
}
});
}
};
//running signals
recyclerView.setAdapter(FBRA);
//closed signals
recyclerView2.setAdapter(FBRA);
}
public static class BlogzoneViewHolder extends RecyclerView.ViewHolder {
View mView;
public BlogzoneViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setPair(String pair) {
TextView post_pair = mView.findViewById(R.id.quote);
post_pair.setText(pair);
}
public void setBuySell(String buySell) {
TextView post_buysell = mView.findViewById(R.id.type);
post_buysell.setText(buySell);
}
public void setOpenPrice(String openPrice) {
TextView post_openprice = mView.findViewById(R.id.entry);
post_openprice.setText(openPrice);
}
public void setTakeProfit(String takeProfit) {
TextView post_takeprofit = mView.findViewById(R.id.tp);
post_takeprofit.setText("Tp: " + takeProfit);
}
public void setStopLoss(String stopLoss) {
TextView post_stoploss = mView.findViewById(R.id.sl);
post_stoploss.setText("Sl: " + stopLoss);
}
public void setProfitPips(String profitPips) {
//nothing
}
public void setLossPips(String lossPips) {
//nothing
}
public void setRewardingP(String comment) {
//nothing
}
public void setComment(String comment) {
//nothing
}
public void setRewarding(String rewarding) {
//nothing
}
public void setResult(String result) {
TextView post_result = mView.findViewById(R.id.status);
post_result.setText("result");
if (!post_result.getText().toString().trim().matches("Take Profit Hit")) {
post_result.setTextColor(Color.parseColor("#ffcc0000"));
} else if (!post_result.getText().toString().trim().matches("Stop Loss Hit")) {
post_result.setTextColor(Color.parseColor("#ff669900"));
} else if (!post_result.getText().toString().trim().matches("Pending...")) {
post_result.setTextColor(Color.parseColor("#000"));
} else {
post_result.setTextColor(Color.parseColor("#ffffff"));
}
}
}}
Help I am stack!
List<Blogzone> openedZones = new ArrayList<>();
List<Blogzone> closedZones = new ArrayList<>();
openedZones.addAll(mDatabase.stream().filter(zone -> zone.isOpened()).collect(Collectors.toList()));
closedZones.addAll(mDatabase.stream().filter(zone -> zone.isClosed()).collect(Collectors.toList()));
FirebaseRecyclerAdapter<Blogzone, BlogzoneViewHolder> FBRAopened = new FirebaseRecyclerAdapter<Blogzone, BlogzoneViewHolder>(
Blogzone.class,
R.layout.card_items,
BlogzoneViewHolder.class,
openedZones
) {
...
}
FirebaseRecyclerAdapter<Blogzone, BlogzoneViewHolder> FBRAclosed = new FirebaseRecyclerAdapter<Blogzone, BlogzoneViewHolder>(
Blogzone.class,
R.layout.card_items,
BlogzoneViewHolder.class,
closedZones
) {
...
}
//running signals
recyclerView.setAdapter(FBRAopened);
//closed signals
recyclerView2.setAdapter(FBRAclosed);

Update list view after navigating back to previous activity

Excuse my noobness. I just don't understand how to implement it to work with my code. What I'm doing is editing a name that's in a list view. When editing the name in "EditDeleteList" and get back to the previous activity (ListView) to see the name updated within the list view, nothing happens. I have to go out of the activity completely to see the change reflected. How do I get this to update? I implement an onActivityReult() method but then get this error message "java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference" so I removed it completely. How I could get the list view to update without getting that error message?
ListView.Java
public class ListView extends AppCompatActivity {
private static final String TAG = "ListView";
DatabaseHelper mDatabaseHelper;
Button btnAdd;
private EditText editText;
private android.widget.ListView listView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
mDatabaseHelper = new DatabaseHelper(this);
btnAdd = (Button) findViewById(R.id.btnAdd);
editText = (EditText) findViewById(R.id.editText);
listView = (android.widget.ListView) findViewById(R.id.lv);
ArrayList<String> list = getIntent().getStringArrayListExtra("myList");
android.widget.ListView lv = (android.widget.ListView) findViewById(R.id.lv);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
//Takes user back to the main activity
ImageView ivBack = (ImageView) findViewById(R.id.ivBackArrow);
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: pressed back arrow");
Intent intent = new Intent(ListView.this, MainActivity.class);
startActivity(intent);
}
});
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newEntry = editText.getText().toString();
if (editText.length() != 0) {
addData(newEntry);
editText.setText("");
} else {
toastMessage("you must put something in the text field");
}
}
});
populateListView();
}
public void addData(String newEntry) {
boolean insertData = mDatabaseHelper.addData(newEntry);
if (insertData) {
toastMessage("Successfully inserted");
recreate();
} else {
toastMessage("Whoops, something went wrong");
}
}
private void toastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
private void populateListView() {
Log.d(TAG, "populateListView: displaying data in the listview");
//get data and append to list
Cursor data = mDatabaseHelper.getData();
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext()) {
//get the value from the database in column 1
//set it to the arraylist
listData.add(data.getString(1));
}
//create arraylist and set it to the adapter
ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
listView.setAdapter(adapter);
//set onclick listen to edit activity
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
String name = adapterView.getItemAtPosition(position).toString();
Log.d(TAG, "onItemClick: you clicked on " + name);
Cursor data = mDatabaseHelper.getItemID(name); //get the id associated with that name
int itemID = -1;
while (data.moveToNext()) {
itemID = data.getInt(0);
}
if (itemID > -1) {
Log.d(TAG, "onItemID: the ID is: " + itemID);
Intent editScreenIntent = new Intent(ListView.this, EditDeleteList.class);
editScreenIntent.putExtra("id",itemID);
editScreenIntent.putExtra("name",name);
startActivity(editScreenIntent);
} else {
toastMessage("No ID found");
}
}
});
}
}
EditDeleteList.java
public class EditDeleteList extends AppCompatActivity {
private static final String TAG = "EditDeleteList";
DatabaseHelper mDatabaseHelper;
private ImageView ivDelete;
private ImageView ivApprove;
private EditText editHashtag;
private String selectedName;
private int selectedID;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_delete);
mDatabaseHelper = new DatabaseHelper(this);
editHashtag = (EditText) findViewById(R.id.editHashtag);
ivDelete = (ImageView) findViewById(R.id.ivDelete);
ivApprove = (ImageView) findViewById(R.id.ivApprove);
//get the intent extra from the ListView activity
final Intent receivedIntent = getIntent();
//get item ID passed as an extra
selectedID = receivedIntent.getIntExtra("id", -1);
//get name passed as an extra
selectedName = receivedIntent.getStringExtra("name");
//set text field to selected item text
editHashtag.setText(selectedName);
ivApprove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String item = editHashtag.getText().toString();
if (!item.equals(null)) {
mDatabaseHelper.updateName(item, selectedID, selectedName);
} else {
toastMessage("you must enter a #hashtag");
}
finish();
}
});
}
private void toastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
In the EditDeleteList.java I have an onClickListener that saves the changes and goes back to the previous activity by using finish();
ivApprove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String item = editHashtag.getText().toString();
if (!item.equals(null)) {
mDatabaseHelper.updateName(item, selectedID, selectedName);
} else {
toastMessage("you must enter a #hashtag");
}
finish();
}
});
Notify the adapter in some part of the activity lifecycle.
OnCreate() should not run when you go back (this is the reason you have to completely recreate the activity to see the list updated) so you should use OnRestart/OnStart/OnResume to notify the adapter to check for new items.
Check this image

Screen rotation - how to override the onSaveInstanceState and onRestoreInstanceState?

I need to keep and restore the results of a search while rotating the screen by override the onSaveInstanceState and onRestoreInstanceState... I don't know how to do this and where to use it.
someone got a clue about this ?
This is a part of the MainActivity:
public class MainActivity extends AppCompatActivity {
private static final String LOG_TAG = MainActivity.class.getName();
/**
* URL for book data from the Google books dataset
*/
private static final String G_BOOKS_REQUEST_URL =
"https://www.googleapis.com/books/v1/volumes?q=";
/**
* Adapter for the list of books
*/
private BookAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
..............
Save the URL search result json/xml in savedInstanceState. When rotate screen test if result exist in savedInstanceState
savedInstanceState.putString("result", <serach result json/xml>);
final EditText searchTextView = (EditText) findViewById(R.id.search_bar);
Button searchButton = (Button) findViewById(R.id.search_button);
ListView bookListView = (ListView) findViewById(R.id.list);
mAdapter = new BookAdapter(this, new ArrayList<Book>());
bookListView.setAdapter(mAdapter);
bookListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Book currentBook = mAdapter.getItem(position);
Uri bookUri = Uri.parse(currentBook.getmUrl());
Intent websiteIntent = new Intent(Intent.ACTION_VIEW, bookUri);
startActivity(websiteIntent);
}
});
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String newQuery = searchTextView.getText().toString();
BookAsyncTask task = new BookAsyncTask();
task.execute(G_BOOKS_REQUEST_URL + newQuery);
}
});
}
#Override
protected List<Book> doInBackground(String... urls) {
// Don't perform the request if there are no URLs, or the first URL is null
if (urls.length < 1 || urls[0] == null) {
return null;
}
List<Book> result = QueryUtils.fetchBookData(urls[0]);
return result;
}
#Override
protected void onPostExecute(List<Book> data) {
mAdapter.clear();
if (data != null && !data.isEmpty()) {
mAdapter.addAll(data);
}
}
}
}

main activity reads the data again from the firebase database after coming back to the mainactivity

this is my MainActivity
private DatabaseReference mDatabaseReference;
private RecyclerView recyclerView;
private PlaceRecyclerAdapter placeRecyclerAdapter;
private List<Places> placesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Places");
placesList = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==R.id.action_add)
{
startActivity(new Intent(MainActivity.this,AddPostActivity.class));
finish();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onStart() {
super.onStart();
mDatabaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Places places = dataSnapshot.getValue(Places.class);
placesList.add(places);
placeRecyclerAdapter = new PlaceRecyclerAdapter(MainActivity.this,placesList);
recyclerView.setAdapter(placeRecyclerAdapter);
placeRecyclerAdapter.notifyDataSetChanged();
}
I am using this RecyclerAdapter to load cardview cards in the main activity
public PlaceRecyclerAdapter(Context context, List<Places> placesList) {
this.context = context;
this.placesList = placesList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.post_row,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Places places = placesList.get(position);
//String imageUrl= null;
holder.place.setText(places.getPlace());
holder.desc.setText(places.getDesc());
//imageUrl= places.getImage();
//todo: Use piccasso library to load images
//Picasso.with(context).load(imageUrl).into(holder.image);
}
#Override
public int getItemCount() {
return placesList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView place;
public TextView desc;
//public ImageView image;
public ViewHolder(View view) {
super(view);
place = (TextView) view.findViewById(R.id.postTitleList);
desc = (TextView) view.findViewById(R.id.postDescList);
//image = (ImageView) view.findViewById(R.id.postImageList);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
int pos = getAdapterPosition();
if (pos != RecyclerView.NO_POSITION) {
Places clickedDataItem = placesList.get(pos);
//Toast.makeText(v.getContext(), "You clicked " + clickedDataItem.getPlace(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, Details.class);
intent.putExtra("NAME", clickedDataItem.getPlace());
intent.putExtra("DESC", clickedDataItem.getDesc());
intent.putExtra("IMG", clickedDataItem.getImage());
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent);
}
}
and here is my Details activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
dPlace = (TextView) findViewById(R.id.detail_title);
dDesc = (TextView) findViewById(R.id.detail_desc);
dImage = (ImageView) findViewById(R.id.detail_image);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
String name = bundle.getString("NAME");
String desc = bundle.getString("DESC");
String img = bundle.getString("IMG");
dPlace.setText(name);
dDesc.setText(desc);
Picasso.with(this).load(img).into(dImage);
now, clicking on a item in MainActivity I am able to go to the Details activity. suppose there are 3 items in database, and at first main activity shows only 3 items. but after going to Details activity, and then coming back to main activity, there are 6 items, the earlier 3 items are repeated. and if again I go to the Details activity and come back, there will be 9 items. I used (Activity)context).finish(); in RecyclerViewAdapter to finish the main activity, but I think it finishes the context from which I am able to get the details.
please help.
Sorry for my bad english.
Your firebase loading data items needs to go inside onCreate() as it will only gets called only once if its on backstack an onStart() will get called twice. So just implement the data item loading logic in onCreate instead of onStart()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDatabaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Places places = dataSnapshot.getValue(Places.class);
placesList.add(places);
placeRecyclerAdapter = new PlaceRecyclerAdapter(MainActivity.this,placesList);
recyclerView.setAdapter(placeRecyclerAdapter);
placeRecyclerAdapter.notifyDataSetChanged();
}
}
Update
placesList.clear();
placesList.add(places);

Unknown Error - Bundling String Array

I keep getting an error for this application every time I press the menu button --> History to start the History.java class. I'm fairly certain it has to do with the Bundle method for sending the two arrays from the TipBookActivity.java class to the History.java class.
Below is the TipBookActivity code:
public class TipBookActivity extends Activity {
/** Called when the activity is first created. */
TextView textTip,textHour,textWage;
EditText editHour,editTip;
float wage;
int precision = 100;
String sTip,sHour;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textTip = (TextView) findViewById(R.id.tvTip);
textHour = (TextView) findViewById(R.id.tvHour);
textWage = (TextView) findViewById(R.id.tvWage);
editTip = (EditText) findViewById(R.id.etTip);
editHour = (EditText) findViewById(R.id.etHour);
Button bSubmit = (Button) findViewById(R.id.bSubmit);
final Bundle bTip = new Bundle();
final Bundle bHour = new Bundle();
final ArrayList<String> tipList = new ArrayList<String>();
final ArrayList<String> hourList = new ArrayList<String>();
bSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textHour.setText(editHour.getText().toString());
textTip.setText(editTip.getText().toString());
wage = Float.parseFloat(textTip.getText().toString()) / Float.parseFloat(textHour.getText().toString());
String tip = String.format("$%.2f",wage);
textWage.setText(String.valueOf(tip) + " an hour");
textHour.setText(editHour.getText() + " Hour(s)");
textTip.setText("$" + editTip.getText());
bTip.putStringArray(sTip,new String[] {editTip.getText().toString()});
bHour.putStringArray(sHour,new String[] {editHour.getText().toString()});
tipList.addAll(Arrays.asList(sTip));
hourList.addAll(Arrays.asList(sHour));
Intent i = new Intent(TipBookActivity.this,History.class);
i.putExtras(bTip);
i.putExtras(bHour);
}
});
}
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
MenuInflater mMain = getMenuInflater();
mMain.inflate(R.menu.main_menu,menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.menuHistory:
startActivity(new Intent("com.smarticle.tipbook.HISTORY"));
return true;
case R.id.menuClear:
//set up next tutorials
Toast display = Toast.makeText(this, "Clear History feature coming soon.", Toast.LENGTH_SHORT);
display.show();
return true;
}
return false;
}
}
The History class code:
public class History extends Activity{
private ListView mainListViewTip;
private ListView mainListViewHour;
private ArrayAdapter<String>listAdapterTip;
private ArrayAdapter<String>listAdapterHour;
String sTip,sHour;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.history_main);
Bundle bTip = this.getIntent().getExtras();
Bundle bHour = this.getIntent().getExtras();
String[] array1 = bTip.getStringArray(sTip);
String[] array2 = bHour.getStringArray(sHour);
ListView mainListViewTip = (ListView) findViewById(R.id.mainListViewTip);
ListView mainListViewHour = (ListView) findViewById(R.id.mainListViewHour);
ArrayList<String> tipList = new ArrayList<String>();
ArrayList<String> hourList = new ArrayList<String>();
tipList.addAll(Arrays.asList(sTip));
hourList.addAll(Arrays.asList(sHour));
listAdapterTip = new ArrayAdapter<String>(this,R.layout.simplerow,tipList);
listAdapterHour = new ArrayAdapter<String>(this,R.layout.simplerow,hourList);
mainListViewTip.setAdapter(listAdapterTip);
mainListViewHour.setAdapter(listAdapterHour);
}
}
Any help on identifying the error cause would be greatly appreciated. The code works (in theory, I think), it just won't work in practice. The general idea is to input two numbers into EditText fields, save them as strings, display them as TextViews, set them as an ArrayList, then bundle and send them to the other class to display in a ListView.
You are not initializing sTip and sHour Strings in both Activities. so initializing sTip and Shour Strings with any constant value as in both Activities:
String sTip="sTip",sHour="sHour";
and from TipBookActivity you are not passing intent to startActivity so first declare Intent i globally then start your Activity as:
TextView textTip,textHour,textWage;
EditText editHour,editTip;
float wage;
int precision = 100;
String sTip,sHour;
Intent i; // declare here
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textTip = (TextView) findViewById(R.id.tvTip);
textHour = (TextView) findViewById(R.id.tvHour);
textWage = (TextView) findViewById(R.id.tvWage);
editTip = (EditText) findViewById(R.id.etTip);
editHour = (EditText) findViewById(R.id.etHour);
Button bSubmit = (Button) findViewById(R.id.bSubmit);
final Bundle bTip = new Bundle();
final Bundle bHour = new Bundle();
final ArrayList<String> tipList = new ArrayList<String>();
final ArrayList<String> hourList = new ArrayList<String>();
bSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textHour.setText(editHour.getText().toString());
textTip.setText(editTip.getText().toString());
wage = Float.parseFloat(textTip.getText().toString()) / Float.parseFloat(textHour.getText().toString());
String tip = String.format("$%.2f",wage);
textWage.setText(String.valueOf(tip) + " an hour");
textHour.setText(editHour.getText() + " Hour(s)");
textTip.setText("$" + editTip.getText());
bTip.putStringArray(sTip,new String[] {editTip.getText().toString()});
bHour.putStringArray(sHour,new String[] {editHour.getText().toString()});
tipList.addAll(Arrays.asList(sTip));
hourList.addAll(Arrays.asList(sHour));
i = new Intent(TipBookActivity.this,History.class);
i.putExtras(bTip);
i.putExtras(bHour);
}
});
}
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.menuHistory:
startActivity(i)); // start Activity here by passing intent
return true;
Approach you are following is completely wrong, you can put one Bundle at a time to the intent, and you are putting two bundles, sTip, and sHours.
Second Bundle sHours will override the first one, and I think its main cause of the null pointer exception, instead you should put all the values(in your case two String Arrays) to a single bundle. and put that bundle to the Intent.
Do as Follows:
public class TipBookActivity extends Activity {
/** Called when the activity is first created. */
TextView textTip,textHour,textWage;
EditText editHour,editTip;
float wage;
int precision = 100;
String sTip="sTip";
String sHour="sHour";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textTip = (TextView) findViewById(R.id.tvTip);
textHour = (TextView) findViewById(R.id.tvHour);
textWage = (TextView) findViewById(R.id.tvWage);
editTip = (EditText) findViewById(R.id.etTip);
editHour = (EditText) findViewById(R.id.etHour);
Button bSubmit = (Button) findViewById(R.id.bSubmit);
final Bundle bundle= new Bundle();
final ArrayList<String> tipList = new ArrayList<String>();
final ArrayList<String> hourList = new ArrayList<String>();
bSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textHour.setText(editHour.getText().toString());
textTip.setText(editTip.getText().toString());
wage = Float.parseFloat(textTip.getText().toString()) / Float.parseFloat(textHour.getText().toString());
String tip = String.format("$%.2f",wage);
textWage.setText(String.valueOf(tip) + " an hour");
textHour.setText(editHour.getText() + " Hour(s)");
textTip.setText("$" + editTip.getText());
bundle.putStringArray(sTip,new String[] {editTip.getText().toString()});
bundle.putStringArray(sHour,new String[] {editHour.getText().toString()});
tipList.addAll(Arrays.asList(sTip));
hourList.addAll(Arrays.asList(sHour));
Intent i = new Intent(TipBookActivity.this,History.class);
i.putExtras(bundle);
}
});
}
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
MenuInflater mMain = getMenuInflater();
mMain.inflate(R.menu.main_menu,menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.menuHistory:
startActivity(new Intent("com.smarticle.tipbook.HISTORY"));
return true;
case R.id.menuClear:
//set up next tutorials
Toast display = Toast.makeText(this, "Clear History feature coming soon.", Toast.LENGTH_SHORT);
display.show();
return true;
}
return false;
}
}
and in History Activity:
public class History extends Activity{
private ListView mainListViewTip;
private ListView mainListViewHour;
private ArrayAdapter<String>listAdapterTip;
private ArrayAdapter<String>listAdapterHour;
String sTip="sTip";
String sHour="sHour";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.history_main);
Bundle bundle= this.getIntent().getExtras();
String[] array1 = bundle.getStringArray(sTip);
String[] array2 = bundle.getStringArray(sHour);
ListView mainListViewTip = (ListView) findViewById(R.id.mainListViewTip);
ListView mainListViewHour = (ListView) findViewById(R.id.mainListViewHour);
ArrayList<String> tipList = new ArrayList<String>();
ArrayList<String> hourList = new ArrayList<String>();
tipList.addAll(Arrays.asList(sTip));
hourList.addAll(Arrays.asList(sHour));
listAdapterTip = new ArrayAdapter<String>(this,R.layout.simplerow,tipList);
listAdapterHour = new ArrayAdapter<String>(this,R.layout.simplerow,hourList);
mainListViewTip.setAdapter(listAdapterTip);
mainListViewHour.setAdapter(listAdapterHour);
}
}

Categories