I have created three different activities with three different ListViews similar to this and created another activity with a Button.
The purpose is to select any item from any ListView and it will change the Button text to the selected item I choose.
Here is the code I use to create the ListViews:
public class C_Camera extends AppCompatActivity {
ListView listView_C_Camera;
String[] listview_c_camera = new String[]{
"a" , "b", "c", "d" , "e" , "f","g", "h","i","j"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_c__camera);
listView_C_Camera = findViewById(R.id.listview_c_camera);
ArrayAdapter<String> CanonCamera = new ArrayAdapter<>(this , R.layout.listview_row,listview_c_camera);
listView_C_Camera.setAdapter(CanonCamera);
listView_C_Camera.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String C_Camera_Temp = listview_c_camera[position];
Intent intent = new Intent(C_Camera.this, BuildCamera.class);
intent.putExtra("C_Camera",C_Camera_Temp);
startActivity(intent);
}
});
}
}
I have another activity with a Button that will get the values of the three different ListViews.
public class BuildCamera extends AppCompatActivity {
Button camerabuild;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_build_camera);
camerabuild = findViewById(R.id.camerabuild);
String C_Camera_Holder = getIntent().getStringExtra("C_Camera");
String N_Camera_Holder = getIntent().getStringExtra("N_Camera");
String S_Camera_Holder = getIntent().getStringExtra("S_Camera");
camerabuild.setText(C_Camera_Holder);
camerabuild.setText(N_Camera_Holder);
camerabuild.setText(S_Camera_Holder);
...
Here I'm facing a problem.
If I use String C_Camera_Holder = getIntent().getStringExtra("C_Camera") and comment the others it will work and change the text,
String C_Camera_Holder = getIntent().getStringExtra("C_Camera");
// String N_Camera_Holder = getIntent().getStringExtra("N_Camera");
// String S_Camera_Holder = getIntent().getStringExtra("S_Camera");
camerabuild.setText(C_Camera_Holder);
// camerabuild.setText(N_Camera_Holder);
// camerabuild.setText(S_Camera_Holder);
but if I uncomment the second one (String N_Camera_Holder = getIntent().getStringExtra("N_Camera")) the first one will stop changing the text and the second will do and so on.
String C_Camera_Holder = getIntent().getStringExtra("C_Camera");
String N_Camera_Holder = getIntent().getStringExtra("N_Camera");
// String S_Camera_Holder = getIntent().getStringExtra("S_Camera");
camerabuild.setText(C_Camera_Holder);
camerabuild.setText(N_Camera_Holder);
// camerabuild.setText(S_Camera_Holder);
the button will always carry the last setText() function that you call.
camerabuild.setText(C_Camera_Holder);
camerabuild.setText(N_Camera_Holder);
camerabuild.setText(S_Camera_Holder); <<----------which is, this one.
to make it dynamic on your activity intents you can use if statement.
like this
if(C_Camera_Holder != null){
camerabuild.setText(C_Camera_Holder);
}else if(N_Camera_Holder != null){
camerabuild.setText(N_Camera_Holder);
}else if(S_Camera_Holder != null){
camerabuild.setText(S_Camera_Holder);
}
Related
I have a many checkbox and I saved in a String if it's checked like this:
String juice = "";
if (apple.isChecked()) {
juice = apple.getText().toString().trim() + " " + etiquetas;
}
if (orange.isChecked()) {
juice = orange.getText().toString().trim() + " " + etiquetas;
}
But when I need in another Activity put the checkbox checked, idk how to checked because I saved in one. I really need to be like this in one variable, because they're instructions for the exam. And thas's my code for the other Activity;
Intent intent = getIntent();
if(intent != null){
String juice_2 = (String) getIntent().getStringExtra("EXTRA_JUICE");
//apple.setChecked();
}
In the current activity, you can use a single String that has multiple juice words separated by a SPACE character.
And at the destination activity, split the string into an array of strings based on the SPACE character, and then set the checkBox value if this array contains your specific juice.
at Activity A:
String juice = "";
if (apple.isChecked()) {
juice = apple.getText().toString().trim() + " ";
}
if (orange.isChecked()) {
juice = orange.getText().toString().trim() + " ";
}
// Going to Activity B
Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putExtra("JUICE", juice);
startActivity(intent);
at Activity B:
if (getIntent() != null) {
String juice = getIntent().getStringExtra("JUICE");
if (juice != null) {
String[] splittedJuice = juice.split(" ");
ArrayList list = new ArrayList();
// Convert array into a List
Collections.addAll(list, oldLines);
// Check if the list contains "orange"
if (list1.contains("orange")) {
orange.setChecked(true);
}
if (list1.contains("apple")) {
apple.setChecked(true);
}
}
}
To pass data from one activity to another you can use Intent.putExtra().
The line will look something like this:
intent.putExtra(LABEL, juice);
where: LABEL is a String which allows second activity to find your variable,
juice is your variable.
To resolve the problem you can use something like this:
public class First extends AppCompatActivity {
private final static String LABEL = "juices";
String juice;
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
final CheckBox apple = (CheckBox) findViewById(R.id.apple);
Button nextIntent = (Button) findViewById(R.id.next);
nextIntent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (apple.isChecked()) {
juice = apple.getText().toString();
}
Intent intent = new Intent(getApplicationContext(), Second.class);
intent.putExtra(LABEL, juice);
startActivity(intent);
}
});
}
}
Second Activity:
public class Second extends AppCompatActivity {
private final static String LABEL = "juices";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
Intent intent = getIntent();
String dataReceived = intent.getStringExtra(LABEL);
System.out.println("Your string: " + dataReceived);
}
}
Anyway, I would recommend that you pass Boolean values to the next activity without converting them to a String if it's only to check/uncheck Checkboxes in the second layout.
If you have a lot of variables in the first activity you can pass them to the array, send it to the another activity (by the similar way) and iterate to check/uncheck boxes.
I have created Activity with a listView which uses setOnItemClickListener to determine which index has been pressed. Then it should pass the data into the next activity based on the selected index.
Passing of the values works, but it only works for the first listView index pressed after the app is reloaded.
To make it more clear. When the app is loaded I can press on any index of the ListView which will pass the data to the next Activity and display it correctly, but then when I go back to the ListView and select different index it still displays the same data from the previous index without updating it. Therefore, I have to reload the app to get new index results displayed.
Here is my ViewListActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_artist);
artistList = (ListView) findViewById(R.id.artistList);
databasehandler = new SqliteHandler(ViewArtistActivity.this);
allArtists = databasehandler.getAllArtists();
artistName = new ArrayList<>();
singleArtistDetails = new ArrayList<>();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (allArtists.size() > 0) {
for (int i=0; i < allArtists.size(); i++) {
ArtistModel artistModel = allArtists.get(i);
artistName.add(artistModel.getArtistName());
}
}
adapter = new ArrayAdapter(ViewArtistActivity.this, android.R.layout.simple_list_item_1, artistName);
artistList.setAdapter(adapter);
artistList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ArtistModel artistModel = allArtists.get(position);
singleArtistDetails.add(artistModel.getArtistName());
singleArtistDetails.add(artistModel.getArtistDOB());
singleArtistDetails.add(artistModel.getArtistBiography());
Intent intent = new Intent(ViewArtistActivity.this, SavedArtistDetailsActivity.class);
intent.putExtra("NAME", singleArtistDetails.get(0));
intent.putExtra("DOB", singleArtistDetails.get(1));
intent.putExtra("BIOGRAPHY", singleArtistDetails.get(2));
startActivity(intent);
}
});
}
Here is my code for displaying selected index results Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saved_artist_details);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
artistSavedNameLbl2 = (TextView) findViewById(R.id.artistSavedNameLbl2);
artistSavedDOBLbl2 = (TextView) findViewById(R.id.artistSavedDOBLbl2);
artistSavedBiographyLbl2 = (TextView) findViewById(R.id.artistSavedBiographyLbl2);
btnDeleteDetails = (Button) findViewById(R.id.btnDeleteDetails);
updateUI();
}
private void updateUI() {
artistSavedNameLbl2.setText(getIntent().getStringExtra("NAME"));
artistSavedDOBLbl2.setText(getIntent().getStringExtra("DOB"));
artistSavedBiographyLbl2.setText(getIntent().getStringExtra("BIOGRAPHY"));
}
Do one thing , initialize [not saying declare] your array list singleArtistDetails inside the onClick method, before adding any values to it.
like
singleArtistDetails = new ArrayList();
Hope this will help.
I am creating an android dictionary app with sounds... I have listview, when an item is selected, a new activity open, inside the new activity contains 4 textviews and an image button, the textviews function perfectly but the image button was not. The audio files are placed in raw folder. How can I put the specific sounds of an item that was clicked?
Here's the code:
MainActivityJava
public class MainActivity extends AppCompatActivity {
ListView lv;
SearchView sv;
String[] tagalog= new String[] {"alaala (png.)","araw (png.)","baliw (png.)","basura (png.)",
"kaibigan (png.)","kakatuwa (pu.)", "kasunduan (png.)","dambuhala (png.)",
"dulo (png.)","gawin (pd.)","guni-guni (png.)","hagdan (png.)","hintay (pd.)",
"idlip (png.)","maganda (pu.)","masarap (pu.)", "matalino (pu.)"};
int[] sounds= new int[]{R.raw.alaala,
R.raw.araw,
R.raw.baliw,
R.raw.basura,
R.raw.kaibigan,
R.raw.kakatuwa,
R.raw.kasunduan,
};
ArrayAdapter<String> adapter;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView1);
sv = (SearchView) findViewById(R.id.searchView1);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,tagalog);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String tagword =tagalog[position];
String[] definition = getResources().getStringArray(R.array.definition);
final String definitionlabel = definition[position];
String[] cuyuno = getResources().getStringArray(R.array.cuyuno);
final String cuyunodefinition = cuyuno[position];
String[] english = getResources().getStringArray(R.array.english);
final String englishdefinition = english[position];
Intent intent = new Intent(getApplicationContext(), DefinitionActivity.class);
intent.putExtra("tagword", tagword);
intent.putExtra("definitionlabel", definitionlabel);
intent.putExtra("cuyunodefinition",cuyunodefinition);
intent.putExtra("englishdefinition", englishdefinition);
startActivity(intent);
}
});
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String text) {
return false;
}
#Override
public boolean onQueryTextChange(String text) {
adapter.getFilter().filter(text);
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
}
DefinitionActivity.java
public class DefinitionActivity extends AppCompatActivity {
MediaPlayer mp;
String tagalogword;
String worddefinition;
String cuyunoword;
String englishword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_definition);
TextView wordtv = (TextView) findViewById(R.id.wordtv);
TextView definitiontv = (TextView) findViewById(R.id.definitiontv);
TextView cuyunotv = (TextView) findViewById(R.id.cuyunotv);
TextView englishtv = (TextView) findViewById(R.id.englishtv);
ImageButton playbtn = (ImageButton) findViewById(R.id.playbtn);
final Bundle extras = getIntent().getExtras();
if (extras != null) {
tagalogword = extras.getString("tagword");
wordtv.setText(tagalogword);
worddefinition = extras.getString("definitionlabel");
definitiontv.setText(worddefinition);
cuyunoword = extras.getString("cuyunodefinition");
cuyunotv.setText(cuyunoword);
englishword = extras.getString("englishdefinition");
englishtv.setText(englishword);
}
playbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
you can pass the raw id in the intent extra and play it on meadiaPlayer
What you want to accomplish is pretty simple.
you can ofcourse pass the id.
But I created this method for your case you can paste it in your activity or class and make a call to it. In my case, I put this method in a class that holds all the common functions, methods, strings, etc. The choice is yours :
public static void playDisSound(Context c, int soundID){
//Play short tune
MediaPlayer mediaPlayer = MediaPlayer.create(c, soundID);
mediaPlayer.setOnCompletionListener( new OnCompletionListener(){
#Override
public void onCompletion( MediaPlayer mp){
mp.release();
}
});
mediaPlayer.start();
}
And this is how to use it in your case :
Example I want to play an audio track from :
int[] sounds= new int[]{R.raw.alaala,
R.raw.araw,
R.raw.baliw,
R.raw.basura,
R.raw.kaibigan,
R.raw.kakatuwa,
R.raw.kasunduan,
};
So I just do :
//TODO ~ pls. remember to define context inside "onCreate" as
//call this before "onCreate"
Context context;
//And do this inside "onCreate" :
context = getApplicationContext();
OR
context = MainActivity.this;
//Then here comes the solution, just make a call to the playDisSound method with the id , in this case the "sounds[postion_referencer_i]"
playDisSound(context, sounds[postion_referencer_i]);
//And now on the question of what your "position_referencer_i" would be .... it also depends on how you intend to pass the id.
Are your going to make a match between the position picked and the position of the sound. It depends on you. But I would have created a set of integers to signify which try I want to play and do a matching simple calculation between the position picked for the item clicked to arrive at the position_referencer_id.
//But simply : note that in your array if I want to play for example "R.raw.baliw" I would just call :
playDisSound(context, R.raw.baliw);
I hope this works perfectly for you. So if I elaborated too much. Do let me know if you may need to stream the sound so I would just paste/send you a very cool method I have been using here in an app am working.
//FINALLY PLS. Remember this : this method would play the sound alright but it wont hesitate to play the sound all over again if you repeat the process. So do remember to check if the sound did play and finished before allowing the user to repeat, if not it could lead to repeated or kind of two speakers playing from the same song but at different time. (And the user may start to think that there is problem with the app. Pls. be very logical and sensitive in using this method)
In solving that, you can disable the button or the UI element that initiates the sound playing until the sound has finished playing, by way of monitoring duration of the track (which I am sure you should know and inculcate into your logic or by simply listening if sound is already playing)
All the best. Era. :)
My program is that when a user enteres some information and clicks the "Submit" button, this data will be stored in a separate activity's list View.I have a Shared Preferences incorporated so that the data will be stored. The problem is that only one piece of information gets stored at a time. If I enter a new piece of data, the previous one is overwritten.
public class PreviousPractices extends Activity {
int minutes,hours;
String description;
String date;
ListView practiceList;
ArrayAdapter<String> adapter;
ArrayList<String> listItems = new ArrayList<String>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.previous_practices_layout);
practiceList=(ListView)findViewById(R.id.practiceList);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,listItems);
practiceList.setAdapter(adapter);
getIntents();
LoadPreferences();
}
public void getIntents(){
if (getIntent().getExtras() == null) {
}
else {
Bundle extras = getIntent().getExtras();
hours = extras.getInt("Hours");
minutes = extras.getInt("Minutes");
description = extras.getString("Description");
date = extras.getString("dateOfPractice");
adapter.notifyDataSetChanged();
SavePreferences("LISTS", date);
}
}
Right now I'm only working with the date to simplify things. I'm not sure what the issue is, and I'd appreciate some help.
Right now I am have a activity screen with edittext lines that I am obtaining user input from. When I hit the create event button on the button, the event text should populate into a news feed that I have on another activity.
Here is the portion CreateEvent activity/screen code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_event);
CreateEvent_Button = (Button)findViewById(R.id.create_event_button);
WhatEvent_Text = (EditText)findViewById(R.id.what_event);
WhenEventTime_Text = (EditText)findViewById(R.id.time_event);
WhenEventDate_Text = (EditText)findViewById(R.id.date_event);
WhereEvent_Text = (EditText)findViewById(R.id.where_event);
CreateEvent_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
WhatEvent_String = WhatEvent_Text.getText().toString();
WhenEventTime_String = WhenEventTime_Text.getText().toString();
WhenEventDate_String = WhenEventDate_Text.getText().toString();
WhereEvent_String = WhereEvent_Text.getText().toString();
Log.e("What: ", WhatEvent_String);
Log.e("When_Time: ", WhenEventTime_String);
Log.e("When_Date: ", WhenEventDate_String);
Log.e("Where_Event: ", WhereEvent_String);
Intent intent = new Intent(CreateEvent.this,MainActivity.class);
intent.putExtra("WhatEvent_String", WhatEvent_String);
intent.putExtra("WhenEventTime_String", WhenEventTime_String);
intent.putExtra("WhenEventDate_String", WhenEventDate_String);
intent.putExtra("WhereEvent_String", WhereEvent_String);
startActivity(intent);
MainActivity main= new MainActivity();
//make sure you call method from other class correctly
main.addEvent();
}
});
}
When the create event button is pressed, it creates an event into the MainActivity screen/activity; however, the user input is null. I am not sure why this is happening because I believe I am using the intent methods correctly.
Here is my MainActivity screen.
Here is the getIntent method in my onCreate method in my MainActivity
Intent intent = getIntent();
if (null != intent) {
test = intent.getStringExtra("WhatEvent_String");
}
However, when I call my addEvent method:
protected void addEvent() {
// Instantiate a new "row" view.
// final ViewGroup newView = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.list_row, mContainerView, false);
// Set the text in the new row to a random country.
// Because mContainerView has android:animateLayoutChanges set to true,
// adding this view is automatically animated.
//mContainerView.addView(newView, 0);
HitupEvent hitupEvent = new HitupEvent();
hitupEvent.setTitle("Rohit "+ "wants to "+test );
hitupEvent.setThumbnailUrl(roro_photo);
//hitupEvent.setRating(30);
//hitupEvent.setYear(1995);
//hitupEvent.setThumbnailUrl(null);
ArrayList<String> singleAddress = new ArrayList<String>();
singleAddress.add("17 Fake Street");
singleAddress.add("Phoney town");
singleAddress.add("Makebelieveland");
hitupEvent.setGenre(singleAddress);
hitupEventList.add(hitupEvent);
adapter.notifyDataSetChanged();
}
The event input text is null. I am not sure why this is happening.
I tried to resolve it but no luck,
How to send string from one activity to another?
Pass a String from one Activity to another Activity in Android
Any idea as for how to resolve this?!
Thanks!
Don't use Intent to get the String you put through putExtra()
Intent intent = getIntent(); // don't use this
if (null != intent) {
test = intent.getStringExtra("WhatEvent_String");
}
Instead Use Bundle, an example snippet
Bundle extra = getIntent().getExtras();
if(extra!=null){
test= extra.getString("WhatEvent_String");
}
EDIT
I noticed just now that you're calling the method main.addEvent() from the wrong place ! Call it in the MainActivity in the onCreate() method.
Remove these lines
MainActivity main= new MainActivity();
//make sure you call method from other class correctly
main.addEvent();
and in your MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourLayout);
Bundle extra = getIntent().getExtras();
if(extra!=null){
test= extra.getString("WhatEvent_String");
}
addEvent(); // call your addEvent() method here
}