Passing JSON to new activity - Android app [duplicate] - java

This question already has answers here:
How do I pass data between Activities in Android application?
(53 answers)
Closed 5 years ago.
This code below returns json into a textView. How do I pass the data within this textview to another activity?
private void showJSON(String response){
String name="";
String address="";
String vc = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
name = collegeData.getString(Config.KEY_NAME);
address = collegeData.getString(Config.KEY_ADDRESS);
vc = collegeData.getString(Config.KEY_VC);
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult.setText("Name:\t"+name+"\nAddress:\t" +address+ "\nVice Chancellor:\t"+ vc);
}
This is the tutorial link I'm following. I know it can be done using intents but I wasn't sure how to use it in this example.
Thanks

String json=textViewResult.getText().toString();
startActivity(new Intent(this,YourActivity.class).putExtra("data",json));
Is this what you want?

Pass String data using putExtra
Intent i = new Intent(youractivity.this, SecondActivity.class);
i.putExtra("name",name);
i.putExtra("address",address);
i.putExtra("vc",vc);
startActivity(i);
In SecondActivity
String name=getIntent().getStringExtra("name");
String address=getIntent().getStringExtra("address");
String vc=getIntent().getStringExtra("vc");
OR
Pass json data from activity
Intent i = new Intent(youractivity.this, SecondActivity.class);
intent.putExtra("jsonObject", jsonObject.toString());
startActivity(i);
In SecondActivity
Intent intent = getIntent();
String jsonString = intent.getStringExtra("jsonObject");
JSONObject jsonObject = new JSONObject(jsonString);

Thank you all for the answers. This has helped me understand how to use intents and I was able to solve my problem with this:
Activity 1
String json= textViewResult.getText().toString();
Intent i = new Intent(Activity1.this, Activity2.class);
i.putExtra("Data",json);
startActivity(i);
Activity 2
Bundle b = getIntent().getExtras();
String json = b.getString("Data");
TextView jData = (TextView) findViewById(R.id.textView1);
jData.setText(json);

Related

How Do i Get all the Values When Sending String Values from one Activity to Another in Android Studio 3.4

Please am designing an android app, i want to send (5)String values from one activity to another activity to use in different TextViews, i have tried virtually all the code i could find online on the topic, but i keep getting just one value(the last value i send in the putExtra()). please i am new to Android Studio and will appreciate every help.
I have used the putExtra() to send one data to another activity and it worked perfectly, while trying to do the same with multiple data i keep getting just one of the data sent.
I have also tried using a bundle object, to receive the data from the other(recieving) activity.
I expect getting all this data ( intent.putExtra("surname", "Jerry").
intent.putExtra("middlename", "chris"). intent.putExtra("lastname", "Enema")) in another activity, but i keep getting just "Enema" alone
this is my code;
//in the firstActivity
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String sFirstname = firstname.getText().toString();
String sLastname = lastname.getText().toString();
Intent intent = new Intent(MainActivity.this, ReceiveActivity.class);
intent.putExtra("surname" ,sFirstname);
intent.putExtra("lastname", sLastname);
startActivity(intent);
}
});
//And In the second Activity
firstname = findViewById(R.id.firstname);
lastname = findViewById(R.id.firstname);
Intent intent = getIntent();
Bundle bundle = getIntent().getExtras();
String ssurname = bundle.getString("surname");
String slastname = bundle.getString("lastname");
firstname.setText(ssurname);
lastname.setText(slastname);
Try this.
In First Activity:
String sFirstname = "Tope";
String sLastname = "Adebodun";
Intent theIntent = new Intent(MainActivity.this, ReceivingActivity.class);
theIntent.putExtra("firstname", sFirstname);
theIntent.putExtra("lastname", sLastname);
Then in your second activity, do this in the onCreate method:
Intent intent = getIntent();
String thefirst = (String) intent.getExtras.getString("firstname");
String thelast = (String) intent.getExtras.getString("lastname");
I would prefer not to ue getExtras so you should have two getExtra
Like this :
Intent intent = getIntent();
String ssurname = intent.getExtra("surname");
String slastname = intent.getExtra("lastname");
firstname.setText(ssurname);
lastname.setText(slastname);

getArguments() in Activity Class?

I'm still learning AS & java and recently bought an app code but it has "getArguments()" inside of fragment which I'd like to convert it into activity. Help is appreciated.
This is the code :
String weburl = getArguments().getStringArray(MainActivity.FRAGMENT_DATA)[0];
String data = getArguments().containsKey(LOAD_DATA) ? getArguments().getString(LOAD_DATA) : null;
if (data != null) {
browser.loadDataWithBaseURL(weburl, data, "text/html", "UTF-8", "");
} else {
browser.loadUrl(weburl);
}
How do I write the same code in an activity?
I think what you are looking for is how to send info to an Activity, for that you need Intents
Please verify this info: https://developer.android.com/reference/android/content/Intent
Basically:
public static final String EXTRA_MESSAGE = "extra message";
...
Intent intent = new Intent(this, SecondActivity.class);
String message = "Hello this is an intent";
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
To retrieve that data you have to do:
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
I invite you to check this out: https://developer.android.com/training/basics/firstapp/starting-activity#java
Intent extras are the activity equivalent of fragment arguments.

How to get the numeric value from intent extra String

I'm using intent to pass the string value to next Activity where I use getStringExtra to get the Value. The value is is User Contact no. in 10 digit which is in numeric value. when I setText in textview then It display the correct format but when I use intent on onclicklistener to open dialpad then instead of no, some random no. appears and in 4 digit also
Here I use to pass string
intent.putExtra(MOBILE, g.getSellermobile());
and I receive it by
tutor_mobile = intent.getStringExtra(MOBILE);
when I set it in textview as
TextView contact = (TextView) findViewById(R.id.tutor_near);
contact.setText(tutor_mobile);
It display correct format eg 9868336847
but when I use intent to open dialpad as
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:"+String.valueOf(tutor_mobile)));
startActivity(intent);
I'm using below code to get the mobile no.
etMobile = (EditText) findViewById(R.id.user_mobile);
String sellermobile = etMobile.getText().toString();
and In class file I have
package com.nepalpolice.filmyduniya.maincategory;
public class location {
public String sellermobile;
// public Uri uri;
public location( String sellermobile) {
this.sellermobile = sellermobile;
// this.uri = uri;
}
public String getSellermobile() { return sellermobile;}
}
}
Then in activity I have
public static final String MOBILE = "other_mobile";
and
intent.putExtra(MOBILE, g.getSellermobile());
and in next activity I have
tutor_mobile = intent.getStringExtra(MOBILE); and
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:"+String.valueOf(tutor_mobile)));
startActivity(intent);
Then random no. in 4 digit appears.
Then in activity I have
Please Help.
Your tutor_mobile is a String value, but thr you rearrange it toString:
intent.setData(Uri.parse("tel:"+String.valueOf(tutor_mobile)));
May be it's not a error, but it's strange. And what do you want to display in dialpad?
try {
Intent callIntent = new Intent(Intent.ACTION_DIAL);
callIntent.setData(Uri.parse("tel:" + "string format number"));
startActivity(callIntent);
} catch (Exception e) {
Log.d("Response", e.toString());
}

Android Login and pasting first and secondnames to user area

Hi guys I need your help, I am stuck in that place. I would like to have first and secondname pasted to user area to appear automatically after logging in. The problem is the user area is in different java class than the one which comes next after log in activity.
Here is the part of the code from log in activity
if(session.loggedin()){
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}
btnlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String email = etemail.getText().toString();
final String password = etpassword.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if(success){
String firstusername = jsonResponse.getString("firstusername");
String secondusername = jsonResponse.getString("secondusername");
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("firstusername", firstusername);
intent.putExtra("secondusername", secondusername);
startActivity(intent);
finish();
session.SetLoggedIn(true);
And here is the code from the user activity
/*
Code for showing users name and last name
*/
final TextView firstUsername = (TextView) findViewById(R.id.firstusername);
final TextView secondUsername = (TextView) findViewById(R.id.secondusername);
Intent intent = getIntent();
String firstusername = intent.getStringExtra("firstusername");
String secondusername = intent.getStringExtra("secondusername");
firstUsername.setText(firstusername);
secondUsername.setText(secondusername);
Now I uploaded some more code.
You approach seems correct. First you should check if your extras are not null( for some reason).
Bundle extras = getIntent().getExtras();
if (extras!= null)
Or if the variables you pass(the one you deserialize from json) to intent are not empty

Sending data from fragment to activity and parse json

I am trying to send 'id' from my fragment activity to an activity and parsing json data based on this 'id' field.
I am successfully sending data from fragment to TourDetail activity, but it is not parsing the json based on same 'id'. The code is not reaching second try block as I examined it using toasts.
Although the same activity(TourDetailActivity.java) is working fine when I pass 'id' from some other activity. Say, if I passed 'id' from jsonuseactivity.java, it is received successfully by TourDetailActivity.java and the respective json result is generated and the appropriate result is displayed.
But if the same 'id' is passed from the fragment activity, it is although receiving the 'id' but not generating the json and no required results based on json are being generated.
TourDetailActivity.java
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tour_detail);
Intent intent = getIntent();
String rcvid = intent.getStringExtra("id");
Toast.makeText(getApplicationContext(), rcvid, Toast.LENGTH_LONG).show();
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("tourid", rcvid));
String response = null;
// call executeHttpPost method passing necessary parameters
try {
Toast.makeText(getApplicationContext(), "in try block", Toast.LENGTH_LONG).show();
response = CustomHttpClient.executeHttpPost(
//"http://129.107.187.135/CSE5324/jsonscript.php", // your ip address if using localhost server
"http://www.futurolicht.com/jsontour.php", // in case of a remote server
postParameters);
String result = response.toString();
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
//parse json data
try {
Toast.makeText(getApplicationContext(), "in 2nd try block", Toast.LENGTH_LONG).show();
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
tname = (TextView) findViewById(R.id.txt_tourtitle);
td = (TextView) findViewById(R.id.txt_day);
tn = (TextView) findViewById(R.id.txt_night);
tdest = (TextView) findViewById(R.id.txt_tourdetail_dest);
btn = (Button) findViewById(R.id.btn_tourdetail);
btn.setOnClickListener(this);
tname.setText(json_data.getString("tour_name"));
tn.setText(json_data.getString("nights"));
td.setText(json_data.getString("days"));
name = json_data.getString("tour_name");
n = json_data.getString("nights");
d = json_data.getString("days");
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
This is my Fragmentone.java's onCreate() method code:
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_one, null);
String fontPath = "fonts/ox.ttf";
b1 = (Button)root.findViewById(R.id.featured_btn1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String id = "34";
Intent intent = new Intent(getActivity(), TourDetailActivity.class);
intent.putExtra("id", id);
getActivity().startActivity(intent);
}
});
I didn't know what actually happened as above code seems okay to me. Instead of sending data, you can make the variable as Static and access that variable in other class like Fragmentone.id. This will definitely work.
Also did you try to catch that id in onStart() instead of onCreate() ? It is convenient to check if there are arguments passed to the fragment in startup

Categories