I am trying to pass some data from one activity to another and I have made a toast in the other activity to see if data is being passed.When the toast shows up it is blank.I have done everything right and tried many different times with different methods I have also created another app but the problem still stays.It gives me null.
My java code in the first activity
public class titleandcuisine extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
public static final String TITLE_GET = "title";
public static final String CUISINE_GET = "cuisine";
ImageView imageView;
Button button;
Spinner spinner;
EditText dish;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_titleandcuisine);
dish = findViewById(R.id.editText);
spinner = findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.cuisines,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
button = findViewById(R.id.next);
imageView = findViewById(R.id.close);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), homepage.class));
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = dish.getText().toString();
String text2 = spinner.getSelectedItem().toString();
Intent data = new Intent(getBaseContext(),imagepost.class);
data.putExtra(TITLE_GET,text);
data.putExtra(CUISINE_GET,text2);
startActivity(data);
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
Second activity java code
public class reviewactivity extends AppCompatActivity {
TextView cuisine,title;
ImageView displayimage,back;
Uri myUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reviewactivity);
Intent intent = getIntent();
String titleget = intent.getStringExtra(titleandcuisine.TITLE_GET);
String cuisineget = intent.getStringExtra(titleandcuisine.CUISINE_GET);
Toast.makeText(this, titleget + cuisineget, Toast.LENGTH_SHORT).show();
cuisine = findViewById(R.id.reviewcuisine);
title = findViewById(R.id.reviewtitle);
back = findViewById(R.id.backtopostvideo);
displayimage = findViewById(R.id.reviewdisplaimage);
// cuisine.setText(cuisineget);
// title.setText(titleget);
// myUri = Uri.parse(uri);
displayimage.setImageURI(myUri);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),videopost.class));
}
});
}
}
You need to read the text from the EditText when the button is clicked. Something like:
title = dish.getText().toString(); // Add this
Intent data = new Intent(getBaseContext(),imagepost.class);
data.putExtra(Intent.EXTRA_TEXT, title);
...
One more thing: You are trying to read the Intent.EXTRA_TEXT at the reviewactivity activity. However, nothing is starting that activity (at least within the piece of code that you shared).
Related
I have a problem with passing data in android. let me explain my problem.
there are two activities called MainActivity and ProductInformationActivity.
in mainActivity there is a settingButton and onClickListener of the button, a bottom sheet dialog will open up. in bottomSheetDialog there are saveButton and three editText. whenever a user click on saveButton it should pass editTexts data's as PercentageClass to productInformationActivity . (percentage Class is a model to save percentages and pass theme between activities).
I create an interface Called "OnPercentageClicked" then I created an instance of this interface and create setter for that (setOnAddPercentageClicked).
in saveButtonListener I create instance of percentege class and set EditTexts data to it and finally I add percentage to interface's method.
this is mainACtivity:
public class MainActivity extends AppCompatActivity {
private View bottomSheetView;
private BottomSheetDialog bottomSheetDialog;
private OnAddPercentageClicked onAddPercentageClicked;
public void setOnAddPercentageClicked(OnAddPercentageClicked onAddPercentageClicked) {
this.onAddPercentageClicked = onAddPercentageClicked;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar mainToolbar = findViewById(R.id.mainToolbar);
setSupportActionBar(mainToolbar);
ImageButton settingbtn = findViewById(R.id.activityMain_settingBTN);
ViewPager2 viewPager2 = findViewById(R.id.activityMain_viewpager);
TabLayout tabLayout = findViewById(R.id.activityMain_tabLayout);
MainViewPagerAdapter adapter = new MainViewPagerAdapter(this);
viewPager2.setAdapter(adapter);
createDialog();
TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(tabLayout, viewPager2, new TabLayoutMediator.TabConfigurationStrategy() {
#Override
public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
switch (position){
case 0 : tab.setText("کالا ها"); break;
case 1 : tab.setText("دسته بندی ها"); break;
}
}
});
tabLayoutMediator.attach();
settingbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bottomSheetDialog.show();
TextInputEditText firstPercentage = bottomSheetDialog.findViewById(R.id.priceIncrementPercentage_firstPercentageET);
TextInputEditText secondPercentage = bottomSheetDialog.findViewById(R.id.priceIncrementPercentage_secondPercentageET);
TextInputEditText thirdPercentage = bottomSheetDialog.findViewById(R.id.priceIncrementPercentage_thirdPercentageET);
Button percentageSaveButton = bottomSheetDialog.findViewById(R.id.priceIncrementPercentage_saveBTN);
assert percentageSaveButton != null;
percentageSaveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (firstPercentage.getText().length()>0 && secondPercentage.getText().length()>0 && thirdPercentage.getText().length()>0){
Percentage percentage = new Percentage();
percentage.setFirstPercentage(Integer.parseInt(firstPercentage.getText().toString()));
percentage.setSecondPercentage(Integer.parseInt(secondPercentage.getText().toString()));
percentage.setThirdPercentage(Integer.parseInt(thirdPercentage.getText().toString()));
onAddPercentageClicked.onButtonClicked(percentage);
bottomSheetDialog.dismiss();
Toast.makeText(MainActivity.this, "ذخیره شد", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(MainActivity.this, "لطفا همه ی فیلد ها را پر کنید", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
public void createDialog(){
bottomSheetDialog = new BottomSheetDialog(MainActivity.this,R.style.bottom_sheet_dialog_theme);
bottomSheetDialog.setContentView(getLayoutInflater().inflate(R.layout.price_increment_percentage,(LinearLayout)findViewById(R.id.priceIncrementPercentage_container),false));
}
}
in productInfomation Activity i want to get the percentage class which i used in MainActivity.
so I implement OnAddPercentageClicked then I create an instance of main activity and call the setter which I created in MainActivity (setOnAddPercentageClicked).
this is productInformationActivity :
public class ProductInformation extends AppCompatActivity implements View.OnClickListener ,OnAddPercentageClicked{
private Percentage percentage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_information);
MainActivity mainActivity = new MainActivity();
mainActivity.setOnAddPercentageClicked(this);
TextView productName = findViewById(R.id.activityProductInformation_productNameTV);
TextView productPrice = findViewById(R.id.activityProductInformation_productPriceTV);
TextView productPriceFirstPercentage = findViewById(R.id.productPriceFirstPercentage);
TextView productPriceSecondPercentage = findViewById(R.id.productPriceSecondPercentage);
TextView productPriceThirdPercentage = findViewById(R.id.productPriceThirdPercentage);
TextView productCategoryName = findViewById(R.id.activityProductInformation_categoryNameTV);
ImageButton close = findViewById(R.id.activity_product_information_closeIB);
close.setOnClickListener(this);
if (percentage !=null){
productPriceFirstPercentage.setText("قیمت کالا +"+percentage.getFirstPercentage()+" درصد");
productPriceSecondPercentage.setText("قیمت کالا +"+percentage.getSecondPercentage()+" درصد");
productPriceThirdPercentage.setText("قیمت کالا +"+percentage.getThirdPercentage()+" درصد");
}
//
// }
if (getIntent().hasExtra("PRODUCT")){
Product product = getIntent().getParcelableExtra("PRODUCT");
productName.setText(product.getTitle());
productPrice.setText(String.valueOf(product.getPrice()));
productCategoryName.setText(String.valueOf(product.getCategoryId()));
}
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.activity_product_information_closeIB){
finish();
}
}
#Override
public void onButtonClicked(Percentage percentage) {
Log.i(TAG, "onButtonClicked: " + percentage);
this.percentage = percentage;
}
}
and when i run this code i get an error which says that the interface in MainActicvity is null.
would you please help me ?
thanks.
Been trying to add a favorites system to this notes app where I can tap and hold an item in the list view to add it to another activity with a list view. Here is the activity with the first list.
Items are added via the MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.savebutton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editTextHeading = (EditText) findViewById(R.id.editTextTextPersonName);
EditText editTextContent = (EditText) findViewById(R.id.contentfield);
String heading = editTextHeading.getText().toString().trim();
String content = editTextContent.getText().toString().trim();
if (!heading.isEmpty()) {
if(!content.isEmpty()) {
try {
FileOutputStream fileOutputStream = openFileOutput(heading + ".txt", Context.MODE_PRIVATE); //heading will be the filename
fileOutputStream.write(content.getBytes());
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else {
editTextContent.setError("Content can't be empty!");
}
}else{
editTextHeading.setError("Heading can't be empty!");
}
editTextContent.setText("");
editTextHeading.setText("");
}
});
Button button2 = (Button) findViewById(R.id.btn_gotosaved);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, saved.class));
}
});
Button button3 = (Button) findViewById(R.id.btn_faves);
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, favorites.class));
}
});
}
}
Items added will be viewed here
public class saved extends MainActivity {
public static final String EXTRA_MESSAGE = "com.example.notes.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saved);
File files = getFilesDir();
String[] array = files.list();
ArrayList<String> arrayList = new ArrayList<>();
final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList);
for (String filename : array) {
filename = filename.replace(".txt", "");
System.out.println(filename);
adapter.add(filename);
}
final ListView listView = (ListView) findViewById(R.id.lv_saved);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = listView.getItemAtPosition(position).toString();
Intent intent = new Intent(getApplicationContext(), Note.class);
intent.putExtra(EXTRA_MESSAGE, item);
startActivity(intent);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
String item = listView.getItemAtPosition(position).toString();
}
});
}
}
And tapping and holding an item from there should "favorite" it and copy it to this new activity with another listview
public class favorites extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorites);
ListView listView = (ListView) findViewById(R.id.lv_favorites);
}
}
How should I approach this?
With your implementation of creating an individual .txt file in the default directory for each note, this is how you could implement:
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
String item = listView.getItemAtPosition(position).toString();
Boolean isItemFavorite = item.contains("_favorite");
if (!isItemFavorite){
File itemFile = new File(item + ".txt");
File favoriteItemFile = new File(item + "_favorite.txt");
itemFile.renameTo(favoriteItemFile);
}
}
});
Then in your "favorites" activity you could access all of your note .txt file the same as you do in your "saved" activity - just filtering out any items that don't contain "_favorite" in your "String[] array = files.list();"
Also, some tips: follow naming convention with your activities. "saved" should at least start with an uppercase letter and really should be named something like "SavedNotesListActivity". Also, you should use a room database to keep track of your notes. You should have a favorites table in your room database to keep track of all of your favorites.
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 am semi-ok with the understanding of how you store and retrieve data through intents, what I am not sure about however is the code implementation. What I want to accomplish is to pass stored data (name/value pairs and a bundle object) to my ThirdActivity class from MainActivity class. Here is a snippet what i have attempted thus far (which when the user clicks on the a3button it just displays a blank page with no string):
MainActivity from which I want to store data to send to ThirdActivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button a2_button = (Button) findViewById(R.id.a2_button);
a2_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent a2intent = new Intent("com.tester.lab.x");
startActivityForResult(a2intent, 1);
}
});
Button a3_button = (Button) findViewById(R.id.a3_button);
a3_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent a3intent = new Intent(v.getContext(), ThirdActivity.class);
a3intent.putExtra("greeting","my Name");
startActivity(a3intent);
}
});
}
}
ThirdActivity:
public class ThirdActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
getIntent().getStringExtra("greeting");
}
}
How would I display the string "my Name" once the user clicks ThirdActivity button? Any help is wonderful, thanks!
Everything is good, just add String type for value that you are getting and use this String as you want (to show in TextView else..):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
EditText text = (EditText) findViewById(R.id.your_textView_id);
String value = getIntent().getStringExtra("greeting");
text.setText(value);
}
Or by using Button:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
EditText text = (EditText) findViewById(R.id.your_textView_id);
Button three = (Button) findViewById(R.id.your_button_id);
three.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String value = getIntent().getStringExtra("greeting");
text.setText(value);
}
});
}
I am working on an app and I need to pass the contents of some textviews to a new activity, but I want to save the content I pass while the app is open so that the user can select more items from other activities and send them to the final checkout activity.
right now I have spinners which save the selection to a Textview
public class Americano extends AppCompatActivity {
// MyDBHandler dbHandler;
String result;
TextView tvSize;
Spinner spinner;
int mPos;
String mSelection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_americano);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Spinner spinnerSize = (Spinner) findViewById(R.id.spinner_size);
AdapterView.OnItemSelectedListener listener = new myOnItemSelectedListener();
spinnerSize.setOnItemSelectedListener(listener);
Spinner spinnerSyrups = (Spinner) findViewById(R.id.spinner_syrups);
AdapterView.OnItemSelectedListener listenerSyrups = new myOnItemSelectedListener2();
spinnerSyrups.setOnItemSelectedListener(listenerSyrups);
Spinner spinnerTopping = (Spinner) findViewById(R.id.spinner_toppings);
AdapterView.OnItemSelectedListener listenerTopping = new myOnItemSelectedListener3();
spinnerTopping.setOnItemSelectedListener(listenerTopping);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DBAdapter dbAdapter = new DBAdapter(view.getContext());
}
});
}
public class myOnItemSelectedListener implements AdapterView.OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) {
Americano.this.mPos = pos;
Americano.this.mSelection = parent.getItemAtPosition(pos).toString();
TextView resultText = (TextView) findViewById(R.id.tvSize);
resultText.setText(Americano.this.mSelection);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
public class myOnItemSelectedListener2 implements AdapterView.OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) {
Americano.this.mPos = pos;
Americano.this.mSelection = parent.getItemAtPosition(pos).toString();
TextView resultText = (TextView) findViewById(R.id.tvSyrup);
resultText.setText(Americano.this.mSelection);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
public class myOnItemSelectedListener3 implements AdapterView.OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) {
Americano.this.mPos = pos;
Americano.this.mSelection = parent.getItemAtPosition(pos).toString();
TextView resultText = (TextView) findViewById(R.id.tvTopping);
resultText.setText(Americano.this.mSelection);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
I have more menu item classes exactly like this one
I want to pass the textview data to the checkout page. But save that data in that page until the user closes the app.
thanks
You can do it sending the information through an Intent.
In your listener you would go to another actvity like this:
Intent intent = new Intent(getActivity(), NewActivity.class);
intent.putExtra("RESULT_TEXT", resultText);
startActivity(intent);
And on the NewActivity you can get the information like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
Bundle bundle = getIntent().getExtras();
String resultText = bundle.getString("RESULT_TEXT", "");
}
Hope it helps.