I'm trying to send a value from TextView to RecyclerView (in an another Activity).
MainActivity.class
There is i want to use a method onClickYes for send each of word to my recyclerView in an another activity.
public class MainActivity extends AppCompatActivity {
TextView display, progress;
private List<String> worldList;
private ArrayList<RecyclerItems> recyclerItems;
private WordDataBase wordDatabaseForYes;
int counter = 1;
int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
display = findViewById(R.id.dispalay);
progress = findViewById(R.id.progress);
recyclerItems = new ArrayList<>();
worldList = new ArrayList<>();
worldList.add("cat");//i want to display this word firstly
worldList.add("dog");//it after click
worldList.add("monkey");//after it
worldList.add("bird");//after it
worldList.add("fish");//etc
worldList.add("home");//etc
worldList.add("car");//etc
}
public void onClickYes(View view) {
if (i >= worldList.size()) return;
display.setText(worldList.get(i));
progress.setText(counter + "");
//заполняем наш recyclerView
//Intent intent = new Intent(MainActivity.this, YesActivity.class);
//intent.putExtra("word", user + ", вам передали: " + gift);
//startActivity(intent);
i++;
counter++;
}
public void onClickNo(View view) {
Toast.makeText(this, "Size is " + worldList.size(), Toast.LENGTH_SHORT).show();
//recyclerItems.add(new RecyclerItems(worldList.get(i)));
i = 0;
counter = 0;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
Intent intent;
switch (item.getItemId()) {
case R.id.yes:
recyclerItems.add(new RecyclerItems(worldList.get(i)));
intent = new Intent(MainActivity.this, YesActivity.class);
startActivity(intent);
break;
case R.id.no:
intent = new Intent(MainActivity.this, NoActivity.class);
startActivity(intent);
break;
case R.id.about:
Toast.makeText(this, "By SaturnPRO", Toast.LENGTH_SHORT).show();
//openDialogAbout
break;
}
return true;
}
}
My Second Activity
public class YesActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
ArrayList<RecyclerItems> yesWordList;
private WordDataBase wordDatabaseForYes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
yesWordList = new ArrayList<>();
recyclerView = findViewById(R.id.rvYes);
recyclerView.setHasFixedSize(true);
adapter = new RecyclerViewAdapter(yesWordList);
layoutManager = new LinearLayoutManager(this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(layoutManager);
}
}
Also i have an Adapter but i couldn't show it here.
How can i do it? enter code here Please help.
Send the word in intent extras:
case R.id.yes:
recyclerItems.add(new RecyclerItems(worldList.get(i)));
intent = new Intent(MainActivity.this, YesActivity.class);
intent.putExtra("key", worldList.get(i));
startActivity(intent);
break;
In your second activity:
String name = intent.getStringExtra("key");
You can make the wordList a static member. Then you can access it in your adapter.
Related
Is there a way how you can add a string to an arraylist, which then fills a listview when a button is clicked in another activity? To be more clear: In activity A, I have a Listview and a menu item where I can go to Activty B. In Activtiy B I have got an EditText and a button. I want to achieve that everytime I click on the Button in activty B, the new String gets listed in the Listview. As a "clicklistener" I used a boolean. Is there a better way? Because with the code below I can only make one list entry which gets changed by every next button click.
Java Code Activity A:`package com.example.schoolapp;
public class MainActivity extends AppCompatActivity {
TextView tvSubjects;
ListView listView;
static ArrayList<String> arrayList = new ArrayList<>();
static ArrayAdapter<String> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvSubjects = findViewById(R.id.tv_subjects);
listView = findViewById(R.id.listView);
arrayList = new ArrayList<>();
arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,
arrayList);
arrayAdapter.notifyDataSetChanged();
listView.setAdapter(arrayAdapter);
if (NewNoteActivity.buttonClicked){
Intent intent = getIntent();
String string = intent.getStringExtra("Subject");
arrayList.add(string);
arrayAdapter.notifyDataSetChanged();
}
}
//Code for the menu, works fine
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()){
case R.id.item_newSubject:
Intent intent = new Intent(this, NewNoteActivity.class);
startActivity(intent);
return true;
default:
return false;
}
}
}`
Java Code for Activity B:
public class NewNoteActivity extends AppCompatActivity {
EditText et_subject;
Button btn_createSubject;
String subject;
static boolean buttonClicked = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_note);
et_subject = findViewById(R.id.et_subject);
btn_createSubject = findViewById(R.id.btn_createSubject);
btn_createSubject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buttonClicked = true;
subject = et_subject.getText().toString();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("Subject", subject);
startActivity(intent);
}
});
buttonClicked = false;
}
}
I am new to Android development. I have an app in which the user creates multiple names (as if they were players of a game). These "players" appear as a matrix is used in the same activity. (Being possible here to exclude any player).
I want to display all of these players (MainActivity) in another activity (Main2Activity), showing only the first player added and, clicking a button, switch to the second player.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
RecyclerView recyclerView;
TextView textAdd;
EditText etAdd;
ArrayList<Model> models = new ArrayList<Model>();
MyAdapter myAdapter;
int position;
Button prox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prox = findViewById(R.id.prox);
prox.setOnClickListener(new View.OnClickListener() {
//next screen
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
String nome = etAdd.getText().toString();
intent.putExtra("value", nome);
startActivity(intent);
}
});
recyclerView = findViewById(R.id.recyclerView);
textAdd = findViewById(R.id.text_adicionar);
etAdd = findViewById(R.id.et_Adicionar);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
myAdapter = new MyAdapter(getApplicationContext(),
models, new MyAdapter.Onclick() {
#Override
public void onEvent(Model model, int pos) {
position = pos;
etAdd.setText(model.getId());
}
});
recyclerView.setAdapter(myAdapter);
textAdd.setOnClickListener(this);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.text_adicionar: {
insertItem(String.valueOf(etAdd.getText()));
}
break;
}
}
private void insertItem(String name) {
Gson gson = new Gson();
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", name);
Model model = gson.fromJson(String.valueOf(jsonObject), Model.class);
models.add(model);
myAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public class Main2Activity extends AppCompatActivity implements View.OnClickListener {
Button play;
TextView text_player_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
play = findViewById(R.id.play);
text_player_name = findViewById(R.id.text);
play.setOnClickListener(this);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.play: {
String name = getIntent().getExtras().getString("value");
text_player_name.setText(String.valueOf(name));
}
break;
}
}
}
I'm not sure if I fully understand your question, but are you just looking for a way to pass data from one Activity to another?
If so, use .putExtra() with your Intent for starting the next Activity.
In the onCreate method for your second Activity, use .getExtras() to retrieve the data.
In 1st Activity
Intent intent = new Intent(this, Activity2.class);
intent.putExtra("DataName", data);
startActivity(intent);
In the 2nd Activity
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
String[] dataArray = getIntent().getExtras().get("DataName"));
}
EDIT:
public class Main2Activity extends AppCompatActivity implements View.OnClickListener {
Button play;
TextView text_player_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
play = findViewById(R.id.play);
text_player_name = findViewById(R.id.text);
play.setOnClickListener(this);
}
#Override
public void onClick(View v) {
String name = getIntent().getExtras().getString("value");
text_player_name.setText(String.valueOf(name));
}
I do not understand why my code are not working ?
I always have class must either be declared abstract or implement abstract method :
public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {
MyRecyclerViewAdapter adapter;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
return true;
case R.id.navigation_public:
return true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navView = findViewById(R.id.nav_view);
mTextMessage = findViewById(R.id.message);
navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
ArrayList<String> mImageUrls = new ArrayList<>();
ArrayList<String> mNames = new ArrayList<>();
mImageUrls.add("https://c1.staticflickr.com/5/4636/25316407448_de5fbf183d_o.jpg");
mNames.add("Havasu Falls");
mImageUrls.add("https://i.redd.it/tpsnoz5bzo501.jpg");
mNames.add("Trondheim");
// set up the RecyclerView
RecyclerView recyclerView = findViewById(R.id.recycler_public);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyRecyclerViewAdapter(this, mImageUrls);
adapter.setClickListener(this);
recyclerView.setAdapter(adapter);
}
}
I found the answer... I forget this :
#Override
public void onItemClick(View view, int position) {
Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
}
Sorry...
There is something I want to ask, I have recycle view where is pass from adapter to activity, my question is :
I need to get value/data checkbox from adapter viewHolder Recycleview to activity who is use the adapter for show recycleview
CartAdapter.java
private Context mContext;
private ArrayList<CartModel> mCartList;
public boolean isSelectedAll = true;
public CartAdapter(Context context, ArrayList<CartModel> CartList){
mContext = context;
mCartList = CartList;
}
#NonNull
#Override
public CartViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(mContext).inflate(R.layout.masteritem_cardview_cart, viewGroup, false);
return new CartViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull CartViewHolder cartViewHolder, int i) {
CartModel currentItem = mCartList.get(i);
cartViewHolder.mCartCheckbox.setChecked(true); //i want pass this value
ShoppingCartActivity.java
private RecyclerView mRecyclerView;
private CartAdapter mCartAdapter;
private ArrayList<CartModel> mCartModelList;
private RequestQueue mRequestQueue;
boolean cartfirst;
private Button mButtonCheckout;
public CheckBox mCartCheckAll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shopping_cart);
cartfirst = false;
mNavigationView = findViewById(R.id.navigation_view);
mNavigationView.setNavigationItemSelectedListener(this);
mDrawerLayout = (DrawerLayout) findViewById(R.id.cart_drawer);
mToogle = new ActionBarDrawerToggle(this,mDrawerLayout,R.string.open,R.string.close);
mDrawerLayout.addDrawerListener(mToogle);
mToogle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mRecyclerView = findViewById(R.id.recycler_view_cart);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mCartModelList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJsonCartItem();
mButtonCheckout = findViewById(R.id.checkOut_btn);
mCartCheckAll = findViewById(R.id.cartChecKall_checkBox);
//firsttime checkall
mCartCheckAll.setChecked(true);
mButtonCheckout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(ShoppingCartActivity.this);
builder.setTitle("Confirm Checkout");
builder.setMessage("Do you really want to Checkout?");
builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
for (int i = 0; i < mCartModelList.size(); i++){
//to here, for checking value if true they will checkout, else do nothing
//checkOutChartJSON();
}
}
startActivity(new Intent(getApplicationContext(),ShoppingCartActivity.class));
finish(); //finish current activity
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
}});
builder.setNegativeButton(android.R.string.no, null);
builder.create().show();
}
});
To check validation if checkbox is true they will do function checkOutChartJSON, else do nothing
If you wanna pass the data or value from an adapter to new activity then you can do it by using Intent and if you wanna pass the value to existing activity then interface is the best way to do it.
For new activity.
// Passing data to TargetActivity.class
Intent intent = new Intent(CurrentActivity.this, TargetActivity.class);
intent.putExtra("message", str);
startActivity(intent);
// Get the data in TargetActivity.class
Intent intent=getIntent();
String msg = intent.getStringExtra("message");
For existing activity.
First, make an interface. OnPassingData
public interface OnPassingData {
void onPassing(int value1, String value2,...,int valueN);
}
In the adapter.
OnPassingData onPassingData;
if (onPassingData != null) {
onPassingData .onPassing(value1, value2,..,valueN);
}
public void setOnPassingData(OnPassingData onPassingData) {
this.onPassingData= onPassingData;
}
At the adapter calling in activity.
adapter.setOnPassingData((value1, value2,...,valueN) -> {
Log.i(TAG, "value1 : " + value1);
Log.i(TAG, "value2 : " + value2);
});
So I have the action bar back button which returns me from an activity to my main activity. The problem I have is that it calls loadData() (which loads data from an API) when you press the action bar back button.
If I press the back button on the device (the button beside the home button) then I will be brought back to the previous view (the mainactivity) and won't have to call the API again.
So I'm trying to find a way to mimic the physical back button as an action bar widget.
I don't want MainActivity's code to be called again as it will execute another API call (I can only have 5 per minute) and it is also slower. I just want it to go back to the view I was just at.
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private ArrayList<ListItem> listItems;
private String defaultQuery = "ham";
private String builtURL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
recyclerView = findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems = new ArrayList<>();
loadData(defaultQuery);
}
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
final SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
listItems.clear();
loadData(query);
(menu.findItem(R.id.action_search)).collapseActionView();
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
searchView.setIconified(false);
return true;
}
public void loadData(String query) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading recipes...");
progressDialog.show();
Log.d("q", "loadData: " + query);
builtURL = buildURL(query);
StringRequest request = new StringRequest(Request.Method.GET,
builtURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
if(response == null) {
response = "THERE WAS AN ERROR";
}
try {
JSONObject obj = new JSONObject(response);
JSONArray hits = obj.getJSONArray("hits");
for (int i = 0; i < hits.length(); i++) {
JSONObject a = hits.getJSONObject(i);
JSONObject recipe = a.getJSONObject("recipe");
String ingredients = recipe.getString("ingredientLines");
ingredients = ingredients.replace("[", "");
ingredients = ingredients.replace("]", "");
ingredients = ingredients.replace("\"", "");
ingredients = ingredients.replace("\\", "");
ingredients = ingredients.replace(",", "\n");
ListItem item = new ListItem(
recipe.getString("label"),
recipe.getString("source"),
recipe.getString("image"),
ingredients,
recipe.getString("url")
);
listItems.add(item);
}
adapter = new Adapter(listItems, getApplicationContext(), builtURL);
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue rq = Volley.newRequestQueue(this);
rq.add(request);
}
private String buildURL(String query) {
Log.d("q", "buildURL: " + query);
Uri.Builder builder = new Uri.Builder();
//url built here but I removed it because it shows API key etc.
String urlToSend = builder.build().toString();
//debugging purposes to show the url created
Log.d("url", "doInBackground: " + urlToSend);
return urlToSend;
}
#Override
public boolean onNavigateUp(){
finish();
return true;
}
This is the activity that I'm coming from.
public class recipe_view extends AppCompatActivity {
ImageView ivRecipeImage;
TextView tvRecipeName;
TextView tvRecipeCreator;
TextView tvRecipeIngredients;
String url;
Integer pos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipe_view);
Bundle data = getIntent().getExtras();
ArrayList<ListItem> list = data.getParcelableArrayList("list");
pos = data.getInt("pos");
for (int i = 0; i < list.size() ; i++) {
System.out.println(list.get(i));
System.out.println(pos);
}
ivRecipeImage = findViewById(R.id.recipeImage);
tvRecipeName = findViewById(R.id.recipeName);
tvRecipeCreator = findViewById(R.id.recipeCreator);
tvRecipeIngredients = findViewById(R.id.ingredients);
tvRecipeName.setText(list.get(pos).getTitle());
tvRecipeCreator.setText(list.get(pos).getAuthor());
Picasso.with(getApplicationContext())
.load(list.get(pos).getImageUrl())
.centerCrop()
.fit()
.into(ivRecipeImage);
tvRecipeIngredients.setText(list.get(pos).getListOfIngredients());
url = list.get(pos).getRecipeUrl();
final Button button = findViewById(R.id.bViewInstructions);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent goToBrowser = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(goToBrowser);
}
});
}
}
In your manifest xml
set
<activity
android:name=".your_activity"
android:label="#string/title_activity_sign_up"
android:parentActivityName=".whateveractivity"
android:screenOrientation="portrait" >
</activity>
then in code
#Override
public void onBackPressed() {
NavUtils.navigateUpFromSameTask(this);
// Otherwise defer to system default behavior.
super.onBackPressed();
}
To elaborate what you are doing is overriding the onbackpressed hardware button.
Also make your parent activity's launchmode singleInstance.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent goToBrowser = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(goToBrowser);
finish();
}
});