Hello I am trying to pass Json Data from Adapter to another Activity
playb = (ImageButton) row.findViewById(R.id.playbtn);
playb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Song newitem = getItem(position);
//long itemId = getItemId(position);
app = (myapplication) getContext().getApplicationContext();
app.setSong(item);
Intent intent1 = new Intent(getContext(), SongDetailedActivity.class);
intent1.putExtra("SongID", item.toString());
getContext().startActivity(intent1);
}
});
and my activity
Intent i = getActivity().getIntent();
hello = i.getIntExtra("SongID", 5);
Song event = app.getSongID(hello);
event.setSongID(hello);
In your activity,
Bundle bundle = getIntent().getExtras();
if(bundle != null && bundle.containsKey("SongID")){
String json = bundle.getString("SongID");
JSONObject jsonObject = new JSONObject(json);
//parse json from here...don't forget to handle JSONException
}
You can whether pass an integer value and catch it using i.getIntExtra()
or pass a String and catch using i.getStringExtra()
You can't put a string in intent and get it as integer, should has the same type.
Related
I am trying to query JSON data on a background thread using AsyncTask and use one of the values from the query in onCreate of the same Activity. How should I do this? Should I use intents or is there a more intuitive and better way of doing it?
In my code below, I am trying to pull the youtube ID using an AsyncTask out of an online database. It works because when I log the value inside the AsyncTask, the correct youtube ID is shown. But I need to use this ID in onCreate so that I can use it to create the full youtube URL. How can I pass the youtube ID string from doInBackground to onCreate? The id is stored in the variable youtubeId
//Activity needs added to manifest.
public class DetailsActivity extends AppCompatActivity {
//LOG tag for debugging
private static final String TAG = "GalleryActivity";
String youtubeIdCode;
//Override on Create and set contentView to new activity_details layout.
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
//Log for debugging so we can tell if activity started successfully.
Log.d(TAG, "onCreate: started.");
loadMovieData();
Intent intent = getIntent();
Movie movie = intent.getParcelableExtra("movie");
String image = movie.getMoviePoster();
String title = movie.getTitle();
String releaseDate = movie.getDate();
String voteAverage = movie.getVoteAverage();
String plot = movie.getPlot();
ImageView poster = findViewById(R.id.details_image);
Picasso.with(this).load(image).into(poster);
TextView name = findViewById(R.id.details_title);
name.setText((getResources().getString(R.string.movie_title)) + " " + title);
TextView dateRelease = findViewById(R.id.details_release_date);
dateRelease.setText((getResources().getString(R.string.release_date)) + " " + releaseDate);
TextView averageVote = findViewById(R.id.details_voter_average);
averageVote.setText((getResources().getString(R.string.vote_average)) + " " + voteAverage);
TextView moviePlot = findViewById(R.id.details_plot);
moviePlot.setText((getResources().getString(R.string.plot)) + " " + plot);
ImageView watchTrailer = findViewById(R.id.imageView);
// watchTrailer.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(trailerUrl.toString()));
// Log.v("OnClick URL",trailerUrl.toString());
// startActivity(intent);
// }
// });
}
public class FetchTrailer extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... strings) {
final String YOUTUBE_ID = "id";
final String RESULTS = "results";
String youtubeId = " ";
Intent intent = getIntent();
Movie movie = intent.getParcelableExtra("movie");
String id = movie.getID();
final URL trailerUrl = NetworkUtils.buildUrlTrailer(id);
Log.v("Built trailer url", trailerUrl.toString());
try {
String jsonResponse = NetworkUtils.getReponseFromHttpUrl(trailerUrl);
JSONObject moviesObject = new JSONObject(jsonResponse);
JSONArray resultsArray = moviesObject.getJSONArray(RESULTS);
for(int i = 0; i < resultsArray.length(); i ++){
JSONObject movieObject = resultsArray.getJSONObject(i);
youtubeId = movieObject.getString(YOUTUBE_ID);
Log.v("youtubeid", youtubeId);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
//Tell the new method to get the data based on the search term within the url.
private void loadMovieData() {
//If there is a network connection, fetch the data.
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
if (isConnected) {
new FetchTrailer().execute();
} else {
Toast toast = Toast.makeText(this, getString(R.string.no_internet_toast), Toast.LENGTH_LONG);
toast.show();
}
}
}
Seems youtubeId is a pre-requisite for your DetailsActivity. So we would need youtubeId prior to DetailsActivity initialization.
In your previous activity from where user can be landed to DetailsActivity , before calling startActivity(intent) call your
loadMovieData()
method as is, you would have to declare method in prior activity. After that pass the youtubeId through intent to DetailsActivity, and you can retrieve value in oncreate():
Intent myIntent = new Intent(CurrentActivity.this,
NextActivity.class);
myIntent.putExtra("youtubeId", value); //Optional parameters
CurrentActivity.this.startActivity(myIntent);
Extras are retrieved on the other side via:
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
String value = intent.getStringExtra("youtubeId"); //if it's a string you
stored.
}
You can use a Callback Listener to achieve this
public interface FetchTrailerListener {
public void onTrailerFetched(String youtubeId);
}
Make DetailsActivity to implement this. Pass this listener reference to asynctask when you are instantiating it.In this way from your postexecute notify the activity through this listener.
protected void onPostExecute( String youtubeId) {
fetchTrailerListenr.onTrailerFetched(youtubeId);
}
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);
In order to pass data from my Custom Adapter to another class I tried these two methods and none worked for me.
String SGetNumVol=Num_Vol.getText().toString();
String SGetComment=Commentaire.getText().toString();
String SGetAirpDepart=Aeroport.getText().toString();
String SGetDestination=Destination.getText().toString();
String SGetCompanie=code_Compagnie.getText().toString();
Intent intent =new Intent(c,DetailVol.class);
Bundle bundle = intent.getExtras();
GetNumVol= bundle.getString(SGetNumVol);
GetComment= bundle.getString(SGetComment);
GetAirpDepart= bundle.getString(SGetAirpDepart);
GetDestination= bundle.getString(SGetDestination);
GetCompanie= bundle.getString(SGetCompanie);
and recieving it like
Intent i = getIntent();
Bundle b = i.getExtras();
if(b!=null)
{
String a =(String) b.get(CustomAdapter.GetAirpDepart);
Airportdep.setText(a);
String c =(String) b.get(CustomAdapter.GetDestination);
dest.setText(c);
String e =(String) b.get(CustomAdapter.GetNumVol);
Num.setText(e);
String f=(String) b.get(CustomAdapter.GetComment);
com.setText(f);
String j =(String) b.get(CustomAdapter.GetCompanie);
Comp.setText(j);
}
Second Method is like :
//SecondTest
Intent i = new Intent(c, DetailVol.class);
String SGetNumVol=Num_Vol.getText().toString();
String SGetComment=Commentaire.getText().toString();
String SGetAirpDepart=Aeroport.getText().toString();
String SGetDestination=Destination.getText().toString();
String SGetCompanie=code_Compagnie.getText().toString();
i.putExtra("SGetNumVol", SGetNumVol);
i.putExtra("SGetComment", SGetComment);
i.putExtra("SGetAirpDepart",SGetAirpDepart);
i.putExtra("SGetDestination",SGetDestination);
i.putExtra("SGetCompanie", SGetCompanie);
recieving :
//SecondTest
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
NumVol= null;
Comment= null;
AirDepart= null;
Destination= null;
Companie= null;
} else {
NumVol= extras.getString("SGetNumVol");
Comment= extras.getString("SGetComment");
AirDepart= extras.getString("SGetAirpDepart");
Destination= extras.getString("SGetDestination");
Companie= extras.getString("SGetCompanie");
}
} else {
NumVol= (String) savedInstanceState.getSerializable("SGetNumVol");
Comment= (String) savedInstanceState.getSerializable("SGetComment");
AirDepart= (String) savedInstanceState.getSerializable("SGetAirpDepart");
Destination= (String) savedInstanceState.getSerializable("SGetDestination");
Companie= (String) savedInstanceState.getSerializable("SGetCompanie");
}
The first returning NullPointerException and the second just pass without any error but it doesn't return values from Custom Adapter. I hope I explained it well, does anybody know how can I correct this?
There is no need to use sharedprefs just send the data with extras from one activity to other activity
add this in the adapter, convertView is inflated view, person is the item of the list
convertView.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Person p = getItem(position);
Intent i = new Intent(_con,SecondActivity.class);
i.putExtra("DATA", p._fName);
_con.startActivity(i);
}
});
second activity:
_text = (TextView) findViewById(R.id.text);
String data = getIntent().getExtras().getString("DATA");
_text.setText(data);
Try this...
Set the value
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", Context.MODE_PRIVATE);
Editor editor = pref.edit();
editor.putString("Vol", SGetNumVol);
editor.putString("Comment", SGetComment);
editor.apply();
Get the value in another Class
SharedPreferences prefs = getSharedPreferences("MyPref", Context.MODE_PRIVATE);
String vol = prefs.getString("Vol", "No name defined");
String comment = prefs.getString("Comment", "No name defined");
Good evening , I'm having trouble passing a ListView an Activity to another. The Activity code that passes to the other is the following called FiltrarImoveis.class :
for (int i = 0; i < jsonArray.length(); i++) {
Imovel imv = new Imovel();
JSONObject child = jsonArray.getJSONObject(i);
String finalidade=child.getString("finalidadeImovel");
String tipo = child.getString("tipoImovel");
String genero = child.getString("generoImovel");
String descricao = child.getString("descricaoImovel");
String responsavel = child.getString("responsavelImovel");
String telefoneResponsavel = child.getString("telefoneResponsavel");
String situacaoImovel = child.getString("situacaoImovel");
String valor = child.getString("valor");
imv.setFinalidade(finalidade);
imv.setTipo(tipo);
imv.setGenero(genero);
imv.setDescricao(descricao);
imv.setResponsavel(responsavel);
imv.setTelefoneResponsavel(telefoneResponsavel);
imv.setSituacao(situacaoImovel);
imv.setValor(valor);
listaImovel.add(imv);
}
} catch (JSONException e) {
e.printStackTrace();
}
//showParsedJSON.setText(output);
carregar(listaImovel);
}
}
}
public void carregar(ArrayList<Imovel> listaImovel){
Intent intent = new Intent(this,DetalhesImoveis.class);
intent.putExtra("lista",listaImovel);
startActivity(intent);
}
The class that inherits from the ListView is the following , call DetalhesImoveis.class :
private ListView lvImoveis;
ArrayList<Imovel> listaImoveis;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detalhes_imoveis);
listaImoveis = (ArrayList<Imovel>) getIntent().getSerializableExtra("lista");
lvImoveis = (ListView)findViewById(R.id.lvImoveis);
try {
ArrayAdapter<Imovel> adpImovel = new ArrayAdapter<Imovel>(DetalhesImoveis.this, android.R.layout.simple_list_item_1, listaImoveis);
lvImoveis.setAdapter(adpImovel);
//Log.v("LISTAiMOVEIS", "ELEMENTOS DA LISTA: " +listaImoveis.get(0).getDescricao().toString() );
}catch(Exception e){
Log.v("logs","ERROR CAUSED BY THE EXCEPTION LIST: "+e.toString());
}
}
We should not use putExtra()for ArrayList instead of that use putStringArrayListExtra() eg: public void carregar(ArrayList<Imovel> listaImovel){
Intent intent = new Intent(this,DetalhesImoveis.class);
intent.putStringArrayListExtra("lista",listaImovel);
and in DetalhesImoveis.class get the Arraylist like:listaImoveis = getIntent().getStringArrayListExtra("lista");
u can :
getIntent().putParcelableArrayListExtra(listaImovel)
Imovel need to implment Parcelable
u can look sth about Parcelable;
or :
AActvt Put list int application or a static var ;
BActvt get list from application or a static var;
in my app i have a listview(asynctask) getting all the users from external database. Each row of my listview contains an image that the user can interact. When user presses that image i try to start a new intent by using the data that i already have(by using putExtra while starting the intent.) Listview works fine - it gathers all the data from database. But, the putExtra values are same for each row. I will appreciate if you can help me regarding that matter.
Code is as follows;
The important part is below
ImageView showlastonmap = (ImageView)v.findViewById(R.id.showlastonmap);
where i try to add putExtra.
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
//Invitation count
Integer inv = json.getInt("invitation");
setNotifCount(inv);
if(Integer.parseInt(res) == 1) {
// Getting JSON Array from URL
android1 = json.getJSONArray(TAG_LOCATIONDATA);
for (int i = 0; i < android1.length(); i++) {
JSONObject c = android1.getJSONObject(i);
// Storing JSON item in a Variable
final String ver = c.getString("username");
final String dataenlem = c.getString("enlem");
final String databoylam = c.getString("boylam");
final String datazaman = c.getString("zaman");
/*----------to get City-Name from coordinates ------------- */
StringBuffer address = new StringBuffer();
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(Double.parseDouble(dataenlem), Double.parseDouble(databoylam), 1);
if (addresses.size() > 0)
// System.out.println(addresses.get(0).getLocality());
address.append(addresses.get(0).getAddressLine(1))
.append(",").append(addresses.get(0).getAddressLine(2));
} catch (IOException e) {
e.printStackTrace();
}
String datalokasyon = address.toString();
/*----------to get City-Name from coordinates ------------- */
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put("enlem", dataenlem);
map.put("boylam", databoylam);
map.put("zaman", datazaman);
map.put("lokasyon", datalokasyon);
oslist.add(map);
list = (ListView) findViewById(R.id.list);
BaseAdapter adapter = new SimpleAdapter(UserList.this, oslist,
R.layout.listview_userlist,
new String[]{TAG_VER,"zaman","lokasyon"}, new int[]{
R.id.vers,R.id.lastlocationinput,R.id.lastupdatedinput}) {
public View getView (int position, View convertView, ViewGroup parent)
{
View v = super.getView(position, convertView, parent);
ImageView showlastonmap = (ImageView)v.findViewById(R.id.showlastonmap);
showlastonmap.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent login = new Intent(getApplicationContext(),
HaritaLastSolo.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
login.putExtra("enlem", dataenlem);
login.putExtra("boylam", databoylam);
startActivity(login);
}
});
return v;
}
};
SwingBottomInAnimationAdapter animationAdapter = new SwingBottomInAnimationAdapter(adapter);
animationAdapter.setAbsListView(list);
list.setAdapter(animationAdapter);
}
//admob
interstitial.setAdListener(new AdListener() {
public void onAdLoaded() {
displayInterstitial();
}
});
//admob
}
if(Integer.parseInt(res) == 0) {
new SweetAlertDialog(UserList.this, SweetAlertDialog.ERROR_TYPE)
.setTitleText("Oops...")
.setContentText(getString(R.string.userlist_nofriend))
.show();
}
}
else {
return;
}
}catch
(JSONException e) {
e.printStackTrace();
}
}
}
you should do :
Intent login = new Intent(getApplicationContext(),
HaritaLastSolo.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
login.putExtra("enlem", oslist.get(position).get("enlem"));
login.putExtra("boylam", oslist.get(position).get("boylam"));
startActivity(login);
You have to create new object which contains required fields.
class Data {
String dataenlem;
String databoylam;
Data(String dataenlem, String databoylam) {
...
}
}
and then set corresponding to each row data using setTag method
ImageView showlastonmap = (ImageView)v.findViewById(R.id.showlastonmap);
// add this
showlastonmap.setTag(new Data(dataenlem, databoylam));
and get it on your onClick
public void onClick(View v) {
// and this
Data data = (Data)v.getTag();
Intent login = new Intent(getApplicationContext(),HaritaLastSolo.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
login.putExtra("enlem", data.dataenlem);
login.putExtra("boylam", data.databoylam);
startActivity(login);
}