Android Studio onClick button to display ImageView in another activity (part 2) - android

I think i didn't describe properly what i meant in this question part 1 . So i enter more details here . Please have a look .
activityOne.java
EditText get_input;
Button get_button;
String display;
int image_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
get_input=(EditText)findViewById(R.id.input_year);
get_button=(Button)findViewById(R.id.button_submit);
get_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int store_get_input=Integer.parseInt(get_input.getText().toString());
int results;
results=store_get_input%12;
if (results == 0) {
display = "Your number is "store_get_input";
image_id=0;
} else if (result ==1){
display = "Your number is "store_get_input";
image_id=1;
}else{
display = "Your number is others";
image_id=3;
}
Intent home_intent=new Intent(getApplicationContext(),Result_page.class);
home_intent.putExtra("home_store_get_input",display);
home_intent.putExtra("home_store_image_src",image_id);
startActivity(home_intent);
}
});
}
activityTwo.java
public class Result_page extends AppCompatActivity {
TextView get_result;
ImageView get_image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result_page);
get_result=(TextView)findViewById(R.id.display_result);
get_image=(ImageView)findViewById(R.id.image_view);
Intent result_intent=getIntent();
String text=result_intent.getStringExtra("home_store_get_input");
get_result.setText(text);// display what the user has enter
// get_image.setImageResource
//OR other coding to display imageview by using the image_id from activty 1?
}
From both java files, i think it will be clearer and easier for u guys to read. So i stuck at activityTwo.java the last past where I need to key in some codes in order to display the imageview by uising int image_id or other coding.

I don't think you need 2 duplicated questions.
Method 1: https://stackoverflow.com/a/38342798/2670771
Method 2:
In activity 1 just send image id to activity 2
if (results == 0) {
display = "Your number is "store_get_input";
image_id = R.drawable.image0;
} else if {...}
In activity 2 get image id from intent
int defaultIdWhenCouldNotFindImageSourceId = -1;//should use a negative value
int imageId = result_intent.getIntExtra("home_store_image_src", defaultIdWhenCouldNotFindImageSourceId);
if( defaultIdWhenCouldNotFindImageSourceId != imageId) {
//when you can find an valid image id in intent extra, display it
get_image.setImageResource(imageId);
}

Convert the string to integer in second activity and use a switch case for selecting image based on that number. Like :
Intent result_intent = getIntent();
String text = result_intent.getStringExtra("home_store_get_input");
try {
int number = Integer.parseInt(text);
} catch(NumberFormatException e) {
//Exception
}
int imageId = R.Drawable.default_image;
switch(number) {
case 1:
imageId = R.drawable.image1;
break;
case 2:
imageId = R.drawable.image2;
break;
........so on
}
ImageView.setImageResource(imageId);

Related

How to update Activity's textview when returning from another Activity's RecyclerView?

Hello (First of all excuse my English if something is wrong, it's not my first language), I'm developing an app with the IMDB API to keep up to date with your favorite series (no links or anything illegal).
I'm gonna focus on the two activities in which the problem is: The first Activity, ActivitySerieJson contains a recycled view filled with all the seasons in card view. Each card view contains season thumbnail, season number and the users completed view percentage:
ActivitySerieJson.
The second activity, ActivityTemporadaJSON contains another recyclerview, this one is filled with chapters name, thumbnail and an eye-shaped button that, when pressed, marks the chapter as seen on DB. The problem is that when I go back to previous activity the completed view percentage TextView is not being refreshed.
ActivityTemporadaJSon
This is my code:
RecyclerAdapterTemporada
public void bindPhoto(Temporada mtemporada, String idSerie, String tipo) {
temporada = mtemporada;
String Nombre = temporada.getNombreTemporada();
if(Nombre.length() >= 25)
{
Nombre = Nombre.substring(0,22);
Nombre = Nombre + "...";
}
AQuery androidAQuery=new AQuery(mItemImage.getContext());
androidAQuery.id(mItemImage).image(temporada.getPoster(), true, true, 150,0);
//Picasso.with(mItemImage.getContext()).load(mserie.getPoster()).into(mItemImage);
mItemDate.setText(Nombre);
mItemidTMDB.setText(idSerie);
mItemNumTemp.setText(Integer.toString(temporada.getNumeroTemporada()));
mItemNumEps.setText(Integer.toString(temporada.getNumeroEpisodios()));
//THIS CODE SECTION CALCULATES PERCENTAGE
if(tipo.equalsIgnoreCase("SQL"))
{
int porcen=1;
int numEps = temporada.getNumeroEpisodios();
if(numEps == 0){
numEps = 1;
}
porcen = (temporada.getEpisodiosVsitos() * 100) / numEps;
mNumEpsVistoVal.setText(Integer.toString(porcen) + "%");
}
else
{
mNumEpsVisto.setVisibility(View.INVISIBLE);
mNumEpsVistoVal.setVisibility(View.INVISIBLE);
}
}
}
}
RecyclerAdapterEpisodio
public class RecyclerAdapterEpisodio extends
RecyclerView.Adapter<RecyclerAdapterEpisodio.EpisodioHolder> {
private ArrayList<Episodio> mEpisodio;
private int IdSerie;
private RecyclerAdapterEpisodio miAdaptador;
private String Tipo;
private View v;
//5
#Override
public void onClick(View v) {
/*Context context = itemView.getContext();
Intent showPhotoIntent = new Intent(context, Pelicula.class);
showPhotoIntent.putExtra(PHOTO_KEY, peli);
context.startActivity(showPhotoIntent);*/
}
public void bindPhoto(final Episodio mEpisodio, final int mIdSerie, String tipo) {
episodio = mEpisodio;
if (tipo.equalsIgnoreCase("SQL")) {
if(episodio.isVisto()){
mBoton.setBackgroundResource(R.drawable.ojoabierto);
}else{
mBoton.setBackgroundResource(R.drawable.ojocerrado);
}
mBoton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (episodio.isVisto()) {
//mBoton.setBackgroundResource(R.drawable.ojoabierto);
DBHelper mydb = new DBHelper(v.getContext());
mydb.CancelVerEpisodio(episodio.getIdEpisodio());
v.setBackgroundResource(R.drawable.ojocerrado);
episodio.setVisto(false);
} else//else
{
//mBoton.setBackgroundResource(R.drawable.ojocerrado);
DBHelper mydb = new DBHelper(v.getContext());
mydb.VerEpisodio(episodio.getIdEpisodio());
mBoton.setBackgroundResource(R.drawable.ojoabierto);
episodio.setVisto(true);
}
}
});
}
else
{
mBoton.setVisibility(View.INVISIBLE);
}
in your fist activity do the loading inside OnResume(). so that when you comeback to the activity . onResume() method will be first called and you will get the updated data. This is when you have all your other block codes functioning well but you have problem with refreshing your page.
move your loading method from onCreate() to onResume() in the first activity

How to access a TextView located in a Table Layout

I made a TableLayout 3x3 in "Activity A"(Chose a Table Layout, because I thought it suits my needs)
7 of the 9 cells are clickable and open "Activity B" which is a custom number picker I made.
I used an intent to pass an array and other data to activiy B
The idea of my number picker is to set a value in the cell I just clicked in Activiy A(I wanted something like the calendarDatePicker)
In "Activity B" I have a method to update the values from "Activity A" and finish() "Activity B" when an image View is clicked wich works very fine except that it does not set the value for the clicked Text View
How can I set the TextValue from another activity when the TextValue is contained in a Table Layout?
I don't use intent, because honestly I don't know how to handle it when the "Activity B" is closed.
I mean where in "Activity A" should I handle this intent from "Activity B"
Using the debugger I found out that trying to set the text using the TextView Id does not works as it shows a "null" object in the debugger.
Activiy A
package com.example.racu.threebythree;
public class threebythree extends AppCompatActivity {
public static ArrayList<Integer> ColumnA = new ArrayList<Integer>();
public static ArrayList<Integer> ColumnB = new ArrayList<Integer>();
public static ArrayList<Integer> ColumnC = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_three_by_three);
for (int i = 1; i < 28; i++) {
if (i > 0 && i < 10)
ColumnA.add(i);
if (i > 10 && i < 19)
ColumnB.add(i);
if (i > 19 && i < 28)
ColumnC.add(i);
}
}
public void openNumberPicker(View v) {
// I used this to "guess" the location of the cell in the table layout as I could not find a way to do it.
String cellName = v.getResources().getResourceName(v.getId());
String cellLetter = cellName.substring(cellName.lastIndexOf("/") + 1);
// Send intent
Intent intent = new Intent(this, NumberPicker.class);
intent.putExtra("Id", (cellLetter.substring(0, 1) + cellLetter.substring(2)).toUpperCase());
switch (cellLetter.substring(0, 1)) {
case ("a"):
intent.putIntegerArrayListExtra("Column", ColumnA);
break;
case ("b"):
intent.putIntegerArrayListExtra("Column", ColumnB);
break;
case ("c"):
intent.putIntegerArrayListExtra("Column", ColumnC);
break;
}
intent.putExtra("Cell ID", v.getId());
startActivity(intent);
}
}
Avtivity B
package com.example.racu.threebythree;
public class NumberPicker extends AppCompatActivity {
GridView numberPicker;
ArrayList<Integer> numbersToDisplay;
TextView viewToDisplay;
ImageView ok, cancel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_number_picker);
numberPicker = (GridView) findViewById(R.id.arrayNumbers);
viewToDisplay = (TextView) findViewById(R.id.number_to_select);
ok = (ImageView) findViewById(R.id.add_number_to_card);
ok.setClickable(false);
Intent intent = getIntent();
String idFromIntent = intent.getStringExtra("Id");
numbersToDisplay = intent.getIntegerArrayListExtra("Letter");
TextView numberPosition = (TextView) findViewById(R.id.numberPosition);
numberPosition.setText(idFromIntent);
final TextView chosenNumber = (TextView) findViewById(R.id.chosenNumber);
ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this, R.layout.number_for_picker, numbersToDisplay);
numberPicker.setAdapter(adapter);
numberPicker.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
chosenNumber.setText(((TextView) v).getText());
ok.setImageResource(R.drawable.ok_blue);
ok.setClickable(true);
}
});
}
public void updateThreByThree(View v) {
Intent intent = getIntent();
int currentCell = intent.getIntExtra("Cell ID", 0);
String idFromIntent = intent.getStringExtra("Id").substring(0, 1);
TextView chosenNumber = (TextView) findViewById(R.id.chosenNumber);
// Here I try to Set the text to the cell in Activity A, using its R.id, but in the debugger I get a null reference, therefore my app crashes
TextView currentCellToEdit = (TextView) findViewById(currentCell);
currentCellToEdit.setText(chosenNumber.getText());
int temp = Integer.parseInt(chosenNumber.getText().toString());
switch (idFromIntent) {
case "A":
threebythree.ColumnA.remove(Integer.valueOf(temp));
break;
case "B":
threebythree.ColumnB.remove(Integer.valueOf(temp));
break;
case "C":
threebythree.ColumnC.remove(Integer.valueOf(temp));
break;
}
finish();
}
public void cancel(View view) {
finish();
}
}
Thanks to Pavan for the hint I found two more very helpful post here and this one was EXACTLY what I was looking for.
Like that ( make sure you give the TableLayout an id ):
TableLayout tl = (TableLayout)findViewById( R.id.tableLayout );
TextView tv = (TextView)tl.findViewById( R.id.textView );

addition of editext values always returns zero

i have 10 edittext values in activitya,i want to add them and show the result in newactivity.
my code
public class activitya extends Activity implements onclicklistener
{
private EditText editext1;
private EditText editext2;
private EditText editext3;
private EditText editext4;
private EditText editext5;
private Button calculate;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activitya);
calculate =(Button)findviewbyid(R.id.button1);
calculate.setonclicklistener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1:
onadd();
break;
default:
break;
}
}
public void onadd()
{
Bundle bundle = new Bundle();
String value1 = editext1.getText().toString();
String value2 =editext2.getText().toString();
bundle.putString("sendvalue1",value1));
bundle.putString("sendvalue2",value2));
try{
Double Total =Double.parseDouble(value1)+Double.parseDouble(value2);}
catch(NumberFormatException e)
{
e.printstacktrace();
}
bundle.putString("totalvalue",String.valueof(Total));
Intent a = new intent(this,newactivity.class);
a.putExtras(bundle);
startactivity(a);
}
}
in newactivity :
public class newactivity extends activity{
private TextView total;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
total =(TextView)findviewbyid(R.id.text1);
onview();
}
public void onview()
{
Bundle bundle = this.getIntent().getExtras();
String param1 = bundle.getString("totalvalue");
total.setText(param1);
}
it shows the addition correctly only if i enter all the 10 values, strange
if i dont enter even one value it shows zero,
couldnt understand where the problem is
You have a try-catch and you do nothing in the catch. This is usually bad practice since you do not know when anything happens in your code.
In this case, Double.parseDouble is throwing an exception as you are trying to parse empty Strings. "" cannot be parsed to a double. "0" can.
You need to make sure that every edit text contains a valid value which can parse to a double or, test each value before trying to parse it.
To check all EditText length before you add all the values.
Like,
if(EditText1.getText.length()==0){
Toast.makeText(YourActivity.this,"All fields are mandatory ",
Toast.LENGTH_LONG).show();
}else if(EditText2.getText.length()==0){
} else if(){
..........
}else{
}
You will avoid NullPointerException

Refresh ListView with ArrayAdapter after editing an Item

I have a ListView, which displays a list of notes taken from a table in SQLiteDatabase with ArrayAdapter.
public class NotepadActivity extends ListActivity {
protected static final int ADD_NEW_NOTE = 0;
protected static final int EDIT_NOTE = 1;
ArrayAdapter<Note> adapter;
NotesManager manager;
private Note nNoteToDelete;
ArrayList<Note> lstAllNotes;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.btnAddNewNote).setOnClickListener(addNewNote);
manager = new NotesManager(this);
lstAllNotes = manager.getAllNotes();
adapter = new ArrayAdapter<Note>(this, R.layout.note, lstAllNotes);
setListAdapter(adapter);
getListView().setOnItemClickListener(editNote);
registerForContextMenu(getListView());
}
When I click on an Item in this ListView, it takes this Note object to the EditNote activity:
private OnItemClickListener editNote = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Note currNote = (Note)parent.getItemAtPosition(position);
int curr_note_id = currNote.getId();
String curr_note_title = currNote.getTitle().toString();
String curr_note_details = currNote.getDetails().toString();
Intent editNote = new Intent(NotepadActivity.this, EditNote.class);
editNote.putExtra("CURR_NOTE_ID", curr_note_id);
editNote.putExtra("CURR_NOTE_TITLE", curr_note_title);
editNote.putExtra("CURR_NOTE_DETAILS", curr_note_details);
startActivityForResult(editNote, EDIT_NOTE);
}
};
I can edit the title of the note in there and the content. When I hit the Save button, it sends back to the main activity the Strings of Title and the Details and the ID int:
public class EditNote extends Activity implements OnClickListener {
int curr_note_id;
String curr_note_title;
String curr_note_details;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editnote);
curr_note_id = getIntent().getExtras().getInt("CURR_NOTE_ID");
curr_note_title = getIntent().getExtras().getString("CURR_NOTE_TITLE");
curr_note_details = getIntent().getExtras().getString(
"CURR_NOTE_DETAILS");
((EditText) findViewById(R.id.edtTitle)).setText(curr_note_title);
((EditText) findViewById(R.id.edtDetails)).setText(curr_note_details);
findViewById(R.id.btnSave).setOnClickListener(this);
findViewById(R.id.btnCancel).setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSave:
String strNoteTitle = ((EditText) findViewById(R.id.edtTitle)).getText().toString().trim();
String strNoteDetails = ((EditText) findViewById(R.id.edtDetails)).getText().toString().trim();
if (!strNoteTitle.equals("")) {
Intent data = new Intent();
data.putExtra("NOTE_ID", curr_note_id);
data.putExtra("NOTE_TITLE", strNoteTitle);
data.putExtra("NOTE_DETAILS", strNoteDetails);
setResult(RESULT_OK, data);
finish();
} else {
((EditText) findViewById(R.id.edtTitle))
.setError("A note must contain a title");
}
break;
case R.id.btnCancel:
setResult(RESULT_CANCELED);
finish();
break;
}
}
}
And in the main activity it should update the DB and the ListView with the new Title, if there were changes. My code does update the DB, but I don't see the change in the ListView immediately, only if I exit the app and open it again. Here's the code (watch the second case, EDIT_NOTE):
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case ADD_NEW_NOTE:
String noteTitle = data.getExtras().getString("NOTE_TITLE");
String noteDetails = data.getExtras().getString("NOTE_DETAILS");
Note nNewNote = new Note(-1, noteTitle, noteDetails);
adapter.add(nNewNote);
manager.addNote(nNewNote);
break;
case EDIT_NOTE:
int noteID = data.getExtras().getInt("NOTE_ID");
noteTitle = data.getExtras().getString("NOTE_TITLE");
noteDetails = data.getExtras().getString("NOTE_DETAILS");
nNewNote = new Note(noteID, noteTitle, noteDetails);
Toast.makeText(NotepadActivity.this, noteTitle + "\n" + noteDetails, Toast.LENGTH_SHORT).show();
manager.updateNote(nNewNote);
break;
}
}
super.onActivityResult(requestCode, resultCode, data);
}
After manager.updateNote(nNewNote); I tried to use adapter.notifyDataSetChanged(); but that didn't work - I didn't see the change in the ListView. Perhaps I used it wrong, perhaps I should use something else...
So how can I make the ListView refresh? How can I see change immediately, without restarting the app?
Thank you!
When you return from the edit activity, set the list adapter again to refresh the ListView. You have to manually refresh the ListView each time if you want to see any updates. Hope this helps.

How to pass values statically from one page to other in android?

In my projects I kept different images for categories. When I click on each category image I am passing its category id to other page statically and setting the drawable image of that category in the new page.
My Code:
Firstpage.java
public static String categoryid;
category1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
categoryid="0";
Intent myIntent = new Intent(view.getContext(),Nextpage.class);
startActivityForResult(myIntent, 0);
}
});
category2.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
categoryid="1";
Intent myIntent = new Intent(view.getContext(),Nextpage.class);
startActivityForResult(myIntent, 0);
}
});
category3.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
categoryid="2";
Intent myIntent = new Intent(view.getContext(),Nextpage.class);
startActivityForResult(myIntent, 0);
}
});
Nextpage.java
public static String catid = Firstpage.categoryid;
ImageView categorytype=(ImageView)findViewById(R.id.imageView1);
if(catid=="0")
{
categorytype.setBackgroundResource(R.drawable.image1);
}
else if(catid=="1")
{
categorytype.setBackgroundResource(R.drawable.image2);
}
else if(catid=="2")
{
categorytype.setBackgroundResource(R.drawable.image3);
}
First time when I am clicking on the category image it is passing the category id to the next page and that particular image is setting in the nextpage. After that I clicked the back button(android back button) and went to Firstpage.java and again clicked on other image. But this time also the same image stored. The category id didnt changed. The category id is not refreshing...How to refresh the category id? Any suggestion will be thankful.....
You are comparing two strings by == operator, instead you should compare by equals method, try following:
if(catid.equals("0"))
{
categorytype.setBackgroundResource(R.drawable.image1);
}
else if(catid.equals("1"))
{
categorytype.setBackgroundResource(R.drawable.image2);
}
else if(catid.equals(2"))
{
categorytype.setBackgroundResource(R.drawable.image3);
}
Don't use static variables for this. Pass the category ID to your Nextpage activity through the intent. In Firstpage.java:
public static final String CATEGORY_KEY = "category";
category1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(this,Nextpage.class);
myIntent.putExtra(CATEGORY_KEY, "0");
startActivityForResult(myIntent, 0);
}
});
Then retrieve it in the onCreate(Bundle) method of Nextpage.java:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String categoryid = intent.getStringExtra(Firstpage.CATEGORY_KEY);
. . .
}
The reason your method doesn't work is that Nextpage.catid is initialized when the class is loaded, but the assignment statement is not executed again unless the class is unloaded and needs to be reloaded.
I think problem is here you are comparing String values using this if(catid=="0") Which you should be compare it using if(catid.trim().equals("0"))
Update this change in your code and check it.

Categories

Resources