get Jsonobject response item - android

I am trying to pass a jsonobject response id item between activities but it is not appending the value of the id parameter.
Here is my code
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_LONG).show();
Intent sendsms Intent(FirstSignUp.this,SmsCodePage.class);
sendsms.putExtra("id", result.toString());
startActivity(sendsms);
}
Next Activity code:
Bundle extras = getIntent().getExtras();
String idata = extras.getString("id");
calling it:
user.put("id", idata);
What might be the problem?

Related

Passing a string from AsyncTask to onCreate or other Activities

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);
}

Getting JSON and cross to another class in AsyckTask

I'm trying to receive JSON from sever and continue to another class, but can't, not working, this how to look my code
class when I click button:
public void onHistoryCheckIn(View view) {
String nCar = numberCar; // to send number car for receive all data json
String type = "historyChckIn";
PreHistoryCheckIn preHistoryCheckIn = new PreHistoryCheckIn(this);
preHistoryCheckIn.execute(type,nCar); // send the data to recieve json
}
Know I go to doInBackground, and I use the onPostExecute
protected void onPostExecute(String s) {
// jsonResult ==> I NEED THE DATA!!!
Intent intent = new Intent(context, HistoryCheckIn.class); // have Damage
context.startActivity(intent);
// alertDialog.setMessage(jsonResult);
// alertDialog.show();
}
I come to class HistoryCheckIn but without JSON, what I can do?
I want to bring jsonResult and I want to come to HistoryCheckIn.class
You have to set the result as an extra to the Intent e.g.
protected void onPostExecute(String s) {
Intent intent = new Intent(context, HistoryCheckIn.class);
intent.putExtra("result", s);
context.startActivity(intent);
}
and retrieve it by calling in HistoryCheckIn
String jsonResult = getIntent().getStringExtra("result");
the fastest way is to add json to your inent
protected void onPostExecute(String s) {
Intent i =new Intent(context, NextActivity.class);
i.putExtra("json", s)
context.startActivity(intent);
}
on other end call
String s= getIntent().getStringExtra("json");
but it is not the best way

Passing data from first activities to a second , second activity to third activity in android

I have a total of 3 activites. I pass the data from the first activity :
Here's My AsyncTask parseResult method
private void parseResult(String result) {
try {
Log.d("MainActivity", "JSON Result : " + result);
JSONArray response = new JSONArray(result);
for (int i = 0; i < response.length(); i++)
{
JSONObject obj = response.getJSONObject(i);
String movie_d = obj.getString("newsD");
String movie_t = obj.getString("newsT");
String movie_i = obj.getString("newsI");
String movie_s_link=obj.getString("newsS");
String movie_youtube_link=obj.getString("youtubeLink");
Log.d("movie_youtube_link","JSON Result : " + result);
String movie_rev_r=obj.getString("reviewR");
Log.d("documentName","JSON Result : " + result);
Newspojo rev_gd = new Newspojo();
rev_gd.setNewsDescription(movie_dec);
rev_gd.setNewsT(movie_t);
rev_gd.setNewsI(movie_i);
rev_gd.setNewsS(movie_source_l);
rev_gd.setYoutubeLink(movie_youtube_link);
rev_gd.setReviewR(movie_rev_r);
revData.add(rev_gd);
}
} catch (JSONException e) {
e.printStackTrace();
}
In my first activity I am displaying a ListView. When I click a list item at current position i am displaying some fields in Activity 2
I send bundle data when i click a list position. Here's my onClick listener in list position
FirstActivity
reviewlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
Intent intent = new Intent(getActivity(), Movie_rev_fulldis_activity.class);
intent.putExtra("mov_pos", position + "");
startActivity(intent);
}
});
return rootview;
}
Here my position OnClick was working fine. I'm trying to display some fields in Second Activity
Second Activity:
Here i pass some values it was displaying fine my problem is when i bundle my youtubeLink link to the third Activity. I am getting null values , I checked youtubeLink
value and I am getting it from the server and parsing it in TextView okay but my problem is when i bundle youtubeLink from second Activity to third Activity. I am getting null value.
static String youtubeLink;
youtubeLink=Reviews_update.revData.get(mov_pos).getYoutubeLink();
Toast.makeText(Movie_rev_fulldis_activity.this,
youtubeLink, Toast.LENGTH_LONG).show();
movie_t=(TextView)findViewById(R.id.revi_fulldes_movietitle);
rev_r=(TextView)findViewById(R.id.revi_fulldes_movierev_sitename);
movie_d=(TextView)findViewById(R.id.revi_fulldes_moviedisc_text);
//youtube video text static text (video)
youtube_text=(TextView)findViewById(R.id.revi_fulldes_movieyoutube_text);
movie_i=(ImageView)findViewById(R.id.revi_fulldes_movieImage);
//youtube image display id and imageView
youtube_image=(ImageView)findViewById(R.id.revi_fulldes_movieyoutubeImg);
youtube_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent youtube = new Intent(getApplicationContext(), PlayYouTube1st.class);
youtube.putExtra("youtubeLink", youtubeLink);
startActivity(youtube);
// Toast.makeText(Movie_rev_fulldis_activity.this,
// youtubeLink, Toast.LENGTH_LONG).show();
}
});
mov_pos = Integer.parseInt((getIntent().getExtras()).getString("mov_pos"));
movie_t.setText(Reviews_update.revData.get(mov_pos).getNewsT());
rev_r.setText(Reviews_update.revData.get(mov_pos).getReviewR());
movie_d.setText(Reviews_update.revData.get(mov_pos).getNewsD());
Picasso.with(getApplicationContext()).load((Reviews_update.revData.get(mov_pos)).getNewsI()).into(target);
}
Here's my ThirdActivity:
private YouTubePlayerView youTubeView;
String youLink;
Intent intent =getIntent();
youLink=intent.getStringExtra("youtubeLink");
youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
Toast.makeText(PlayYouTube1st.this,
youLink, Toast.LENGTH_LONG).show();
I have been stuck on this error for the past 2 days so could please someone help me find why youtubeLink is showing null values when passing it to 3rd Activity? Thank you!
Put below line
mov_pos = Integer.parseInt((getIntent().getExtras()).getString("mov_pos"));
above
youtubeLink=Reviews_update.revData.get(mov_pos).getYoutubeLink();

How to send a List to next Intent

I want to send this 'list' to the next class(HomeActivity).But i was trying to do it by sending extras but couldn't somebody please help me to fix this
code
protected void onPostExecute(final List<HashMap<String,String>> list) {
// Get json response status
status = "OK";
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
if(status.equals("OK")){
int list_size = list.size();
i = new Intent(getApplicationContext(),
HomeActivity.class);
startActivity(new);
}
}
});
}
You have to prepare/seralize your list data for example in JSON format and then pass it to intent as string extra
JSONArray list = new JSONArray();
list.put(new JSONObject().put("id",1).put("name", "placeNmae"));
intent.putStringExtra("places", list.toString());

Why can I successfully pass a Parcelable but not use putExtra, getStringExtra

I was trying to pass a String from an AsyncTask to a new Activity in AsyncTask.onPostExecute:
protected void onPostExecute(String response) {
Intent displayResponse = new Intent(context, DisplayResponse.class);
displayResponse.putExtra("package_name.DisplayResponse.response", response);
displayResponse.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(displayResponse);
}
where context = (Context) this in the MainActivity which starts the AsyncTask and passes context in the constructor.
In DisplayResponse getIntent().getStringExtra("package_name.DisplayResponse.response") is always null
If I use a simple Parcelable with just one String and pass that from
protected void onPostExecute(String response) {
Intent displayResponse = new Intent(context, DisplayResponse.class);
StringParcel sp = new StringParcel(response);
displayResponse.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Bundle bundle = new Bundle();
bundle.putParcelable("response", sp);
displayResponse.putExtra("package_name.DisplayResponse.response", bundle);
context.startActivity(displayResponse);
}
I can then use the String in DisplayResponse:
Intent intent = getIntent();
Bundle extras = intent.getBundleExtra("package_name.DisplayResponse.response");
StringParcel sp = extras.getParcelable("response");
textView.setText(sp.parcelString);
So the question is why does the first method using putExtra, getStringExtra fail, whereas the second method using a Parcelable work?

Categories

Resources