I am looking for some help with a tutorial I have been working on. I am trying to pass an object when I click on a list item from one activity to another using an Intent. I have posted some of the tutorial code I have been using below but can't seem to get it to work.
My Main Activity code is below:
StringRequest stringRequest = new StringRequest(Request.Method.GET, GET_HEROES_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);
for(int i =0; i<array.length(); i++){
JSONObject obj = array.getJSONObject(i);
Hero hero = obj.getString("name"));
heroList.add(hero);
}
adapter = new HeroAdapter(heroList, getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
And from my Adapter this is the code I have been using this:
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
final Hero hero = heroList.get(position);
holder.textViewName.setText(hero.getName());
holder.textViewName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, HeroDetailActivity.class);
intent.putExtra(KEY_HERO_ID, hero.getName());
context.startActivity(intent);
}
});
}
The intent is listed but it is not carrying the data into my new activity. I just want to take
hero.getName()
at the position it was clicked on in the itemlist and open up a new activity, and in the new activity set it to a TextView. This is part of code I have used on the new activity, but it wont post anything into the TextView.
TextView textViewName
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hero_detail);
textViewname = (textView) findViewById(R.id.textView);
Intent intent = getIntent();
if(intent == null)
return;
int id = intent.getIntExtra(HeroAdapter.KEY_HERO_ID, -1);
err.setText(id);
For instance I click on spiderman set in the list which is at position 3, and in the new activity the textView will load with Spiderman listed. Any help would be appreciated.
You can pass objects using serializable or parcelable interfaces but if you just want the name of your hero you should pass it as string in your intent. Now you're passing an id. You can totally do that. If it's int you should set it correctly to textview
err.setText(String.valueOf(id));
That's why it's not working now.
Or just pass it as string right from the beginning
Intent intent = new Intent(context, HeroDetailActivity.class);
intent.putExtra(KEY_HERO_NAME, hero.getName());
context.startActivity(intent);
And then retrieve it
Intent intent = getIntent();
if(intent == null)
return;
String heroName = intent.getStingExtra(HeroAdapter.KEY_HERO_NAME);
err.setText(heroName);
Try with this:
int id = -1;
if(getIntent().hasExtra(HeroAdapter.KEY_HERO_ID)){
id = getIntent().getExtras().getInt(HeroAdapter.KEY_HERO_ID);
}
err.setText("" + id);
If you need send the hero name then:
In your adapter:
Intent intent = new Intent(context, HeroDetailActivity.class);
intent.putExtra(KEY_HERO_ID, hero.getName());
context.startActivity(intent);
In your activity:
String heroName = "";
if(getIntent().hasExtra(HeroAdapter.KEY_HERO_ID)){
heroName = getIntent().getExtras().getString(HeroAdapter.KEY_HERO_ID);
}
err.setText(heroName);
Related
I am giving the first steps in MVVM, I have a imbd app using retrofit.
At this moment I have a dynamic URL that change the list of movies by passing a different movie id
#GET("3/movie/{movie_id}}/similar?api_key="+api_key+"&language=en-US&page=1")
Call<Similar> getAllSimilarMovies(#Path("movie_id") int movieId);
I have a Repository where I am trying to get the Intent values but the .getIntent doesn't work, the Intent is in the recyclerview passing the ID of the movie clicked
public class DetailsMovieRepository {
private List<ResultSimilar> similarMoviesList;
private MutableLiveData<List<ResultSimilar>> mutableLiveData = new MutableLiveData<>();
public MutableLiveData<List<ResultSimilar>> getSimilarMutableliveData() {
MovieDataService movieDataService = RetrofitInstance.getRetrofitInstance();
Intent intent = getIntent(); // DONT WORK!
int movieId = intent.getIntExtra("movie_id",0);
Call<Similar> call = movieDataService.getAllSimilarMovies(movieId);
call.enqueue(new Callback<Similar>() {
#Override
public void onResponse(Call<Similar> call, Response<Similar> response) {
Similar similar = response.body();
if (similar != null && similar.getResults() != null) {
similarMoviesList = similar.getResults();
mutableLiveData.setValue(similarMoviesList);
}
}
#Override
public void onFailure(Call<Similar> call, Throwable t) {
Log.e("onFailed", " ******" + t.getMessage() + "*******");
}
});
return mutableLiveData;
}
}
The question is how can I get the value from the Intent save as a var and pass here
Call<Similar> call = movieDataService.getAllSimilarMovies(---MY INTENT VALUE---);
Starting Intent in Adapter
private SimilarViewHolder(#NonNull View itemView) {
super(itemView);
movieNameTv = itemView.findViewById(R.id.name_movie_tv);
movieRatingTv = itemView.findViewById(R.id.rating_movie_tv);
moviePosterIV = itemView.findViewById(R.id.movie_poster_iv);
movieDateTv = itemView.findViewById(R.id.date_movie_tv);
movieVotesTv = itemView.findViewById(R.id.votes_movie_tv);
movieOriginalTitleTv = itemView.findViewById(R.id.original_title_tv);
movieLanguageTv = itemView.findViewById(R.id.language_movie_tv);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
ResultSimilar selectedMovie = similarMoviesList.get(position);
Intent intent = new Intent(context, DetailsActivity.class);
Bundle bundle = new Bundle();
bundle.putInt("movie_id",selectedMovie.getId());
intent.putExtras(bundle);
context.startActivity(intent);
Log.e("ddddd" , "***" + selectedMovie.getId());
}});
}
}
Data service
public interface MovieDataService {
String api_key = "5bbf68dcf3b4ad3875ef7b2ed5ddfe1a";
#GET("3/movie/now_playing?api_key="+api_key+"&language=en-US&page=1")
Call<Movies> getAllMovies();
#GET("3/movie/{movie_id}}?api_key="+api_key+"&language=en-US")
Call<MovieResponse> getMovieDetails(#Path("movie_id") int movieId) ;
#GET("3/movie/{movie_id}}/similar?api_key="+api_key+"&language=en-US&page=1")
Call<Similar> getAllSimilarMovies(#Path("movie_id") int movieId);
}
Thank you!
If you want to get data from Intent then you should do it in your Activity class, then you can pass it to you repository from the constructor for example detailsMovieRepository(int id);
i have two intent city and product.first app open city intent show and user select city . now city pass to product intent for show products.
I use array list for fetching data from php api and show to user in product intent:
ArrayList<HashMap<String,String>> getDatalist;
StringRequest stringRequest = new StringRequest(Request.Method.GET, jsonUrl,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
obj = new JSONObject(response);
prdArray = obj.getJSONArray("prd");
for(int aind = 0 ; aind < 2; aind++) {
final JSONObject do_id = prdArray.getJSONObject(aind);
String email = do_id.getString("email");
String phone = do_id.getString("phone");
HashMap<String,String> map = new HashMap<>();
map.put("KEY_EMAIL",email);
map.put("KEY_PHONE",phone);
getDatalist.add(map);
Toast.makeText(getApplicationContext(),user_id, Toast.LENGTH_SHORT).show();
}
}catch (JSONException e) {
Toast.makeText(getApplicationContext(),e.getMessage(), Toast.LENGTH_SHORT).show();
}
anything is OK now.Nut i have a bottom for change city when user click it . city Intent show and after city changed he coma back to product intent.but now products not show :(
Button cityChange=(Button)findViewById(R.id.cityChange);
cityChange.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cityChangeIntent = new Intent(home.this,city.class);
cityChangeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(cityChangeIntent);
finish();
}
});
Recycleviewadapter:
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
if (holder instanceof ViewHolderRow) {
HashMap<String,String> map = mDataset.get(position);
ViewHolderRow userViewHolder = (ViewHolderRow) holder;
userViewHolder.txtEmail.setText(map.get("KEY_EMAIL"));
userViewHolder.txtPhone.setText(map.get("KEY_PHONE"));
.....
Use for loop like this
for(int aind = 0 ; aind < prdArray.size; aind++) {
//your code
}
I am currently using recycler view to load courses using JSON, the first course has its id in JSON that is one, and then the second, each course has its id that is stored in the db. I want that if I click the first button it should save its ID that is one to my session manager and pass it to the next activity to load its corresponding data, and when I click on the 2nd button it should load data by passing its respective ID. I have attached the onclick of my recycler view, it should get the ID of the button clicked and store it into a string that I will then store into the session manager.
private RecyclerView mRecyclerView;
private CourseAdapter mExampleAdapter;
private ArrayList<CourseItem> mExampleList;
private RequestQueue mRequestQueue;
private static final String URL_PRODUCTS = "https://www.sniptx.com/ws/findTeacher/allCourses.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mRecyclerView = (RecyclerView) findViewById(R.id.course_recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, mRecyclerView, new RecyclerItemClickListener
.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Toast.makeText(HomeActivity.this, "Item Clicked" + position , Toast.LENGTH_LONG).show();
}
#Override
public void onItemLongClick(View view, int position) {
//handle longClick if any
}
}));
mExampleList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJSON();
}
private void parseJSON() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_PRODUCTS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
JSONArray courseArray = obj.getJSONArray("courses");
for (int i = 0; i < courseArray.length(); i++) {
JSONObject courseObject = courseArray.getJSONObject(i);
String courseName = courseObject.getString("c_name");
String id = courseObject.getString("c_id").trim();
l.add(new CourseItem(courseName, id));
}
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
JSONObject product = array.getJSONObject(i);
String courseName = product.getString("c_name");
String id = product.getString("id").trim();
mExampleList.add(new CourseItem(courseName, id));
Toast.makeText(HomeActivity.this,"ID is" +id, Toast.LENGTH_SHORT).show();
}
mExampleAdapter = new CourseAdapter(HomeActivity.this, mExampleList);
mRecyclerView.setAdapter(mExampleAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
Volley.newRequestQueue(this).add(stringRequest); }
}
Use Intent to set the data(i.e id of clicked button)as extra params of intent in first activity and get the intent extras in second activity.
// first activity
Intent i = new Intent(getApplicationContext(), SecondActivity.class);
i.putExtra("id", value);
startActivity(i);
// second activity
Bundle extras = getIntent().getExtras();
int id = extras.getInt("id");
I am new to android.
In my Activity class i get a link value by hitting an URL as below code.
try {
JSONArray jsonarray = new JSONArray(response);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("Sno");
String Tktid = jsonobject.getString("TKTID");
link = jsonobject.getString("Link");
List list = new List(jsonobject.getString("Sno"), jsonobject.getString("TKTID"),jsonobject.getString("Link"));
tktList.add(list);
Log.i("website content", name);
Log.i("website content", Tktid);
Log.i("website content", link);
}
//creating custom adapter object
ListViewAdapter adapter = new ListViewAdapter(tktList, getApplicationContext());
//adding the adapter to listview
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
And i am Assigning that value to a button in a Adapter class like below.
TextView textViewName = listViewItem.findViewById(R.id.textViewName);
TextView textViewImageUrl = listViewItem.findViewById(R.id.textViewImageUrl);
Button btupdate = listViewItem.findViewById(R.id.btupdate);
List hero = tktList.get(position);
btupdate.setText(hero.getLink());
btupdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(mCtx, Main3Activity.class);
i.putExtra("Link",view.getId());
mCtx.startActivity(i);
}
});
Now here what my requirement is to Access that assigned link value in an other activity to retrieve some data related to that value.
Please hep me any one.
Use this:
btupdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(mCtx, Main3Activity.class);
i.putExtra("Link",btupdate.getText().toString().trim());
(or)
i.putExtra("Link",hero.getLink());
mCtx.startActivity(i);
}
});
Inside Main3Activity.java
Oncreate(){
Bundle bundle = getIntent().getExtras();
String message = bundle.getString("Link");
}
}
you just replace this below code
TextView textViewName = listViewItem.findViewById(R.id.textViewName);
TextView textViewImageUrl = listViewItem.findViewById(R.id.textViewImageUrl);
Button btupdate = listViewItem.findViewById(R.id.btupdate);
List hero = tktList.get(position);
btupdate.setText(hero.getLink());
btupdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(mCtx, Main3Activity.class);
i.putExtra("Link",hero.getLink());
mCtx.startActivity(i);
}
});
i want to pass the correct json object on the list item click in the first activity to the second activity. If i click any list item, the json object from JSONArray response should be passed to intent and my next activity must get it.
Here is my code
JsonArrayRequest postReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Consumer user = new Consumer();
user.setTitle(obj.getString("name"));
user.setUserid(obj.getString("user"));
user.setThumbnailUrl(obj.getString("image"));
user.setAmountreq(obj.getString("price"));
user.setTime(obj.getString("date"));
user.setCounty(obj.getString("county"));
// adding request to consumer class
userList.add(user);
} catch (JSONException e) {
e.printStackTrace();
}
}
/*notifying list adapter about data changes
so that it renders the list view with updated data*/
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(postReq);
// listening to single list item on click
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(!obj.isNull(position)){
//start new activity
Intent myIntent = new Intent(RequestFeedActivity.this,RequestFeed.class);
myIntent.putExtra("name", obj.getJSONObject(position).toString());
startActivity(myIntent);
}
// ListView Clicked
}
});
}
On the other activity here is my sample code of the variables i want to be passed
TextView rname, rtitle,rprice, rdate, rdesc, rcounty;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.requestfeed);
rtitle = (TextView)findViewById(R.id.IDRproduct);
rprice = (TextView)findViewById(R.id.IDRquote);
rdate = (TextView)findViewById(R.id.IDRdate);
rdesc = (TextView)findViewById(R.id.IDRdesc);
rname = (TextView)findViewById(R.id.IDRname);
Intent myIntent = getIntent();
//Assign values
rname.setText(myIntent.getExtras().getString("name"));
rtitle.setText(myIntent.getExtras().getString("title"));
rprice.setText(myIntent.getExtras().getString("pricetag"));
rdate.setText(myIntent.getExtras().getString("timereq"));
rdesc.setText(myIntent.getExtras().getString("description"));
rcounty.setText(myIntent.getExtras().getString("county"));
}
I tried this answer but didnt work .Any much help is much appreciated
Try to replace this peace of code:
myIntent.getExtras().getString("name")
With this code:
myIntent.getStringExtra("name");
Just try this
Intent i =new Intent(this,ActivityA.class);
Bundle b =new Bundle();
i.putExtra("KEY","VALUE");
i.putExtras(b);
startActivity(i)
At the receiver side
Bundle b=getIntent().getExtras();
b.getInt("KEY") //useaccording to ur need
If it doesn't work check this answer