Getting JSON and cross to another class in AsyckTask - android

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

Related

get Jsonobject response item

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?

How to pass a value through button to another activity in android code?

I have two class DashboardActivity.class and ProfileActivity.class,
In Dashboard class I would like to pass a value through button to ProfileActivity class. But it keep getting me error and the response JSON telling me that the 'Required field(s) is missing'. When I checked, the value from Dashboard didn't pass to ProfileActivity, that's why the response keep telling me 'Required filed(s) is missing'.
My, question is, How to pass a value through button to another activity. I already use this code :
btnLinkToProfile = (Button) findViewById(R.id.btnProfile);
btnLinkToProfile.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
//userFunctions.userProfil(INPUT_METHOD_SERVICE);
Intent i = new Intent(getApplicationContext(),ProfileActivity.class);
i.putExtra(KEY_NAME, name);
startActivityForResult(i,0);
}
But I get forced close when I try to run.
Here's the complete code of Dashboard Activity :
public class DashboardActivity extends Activity {
UserFunctions userFunctions;
Button btnLogout;
Button btnLinkToProfile;
private static final String KEY_NAME = "name";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* Dashboard Screen for the application
* */
// Check login status di database
userFunctions = new UserFunctions();
if(userFunctions.isUserLoggedIn(getApplicationContext())){
// user already logged in show dashboard
setContentView(R.layout.dashboard);
//JSONObject json = jParserr.getJSONFromUrl(dashboardURL, "GET", params);
btnLinkToProfile = (Button) findViewById(R.id.btnProfile);
btnLinkToProfile.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
//userFunctions.userProfil(INPUT_METHOD_SERVICE);
Intent i = new Intent(getApplicationContext(),ProfileActivity.class);
i.putExtra(KEY_NAME, name);
startActivityForResult(i,0);
//startActivity(i);
//finish();
}
});
btnLogout = (Button) findViewById(R.id.btnLogout);
btnLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
userFunctions.logoutUser(getApplicationContext());
Intent login = new Intent(getApplicationContext(), MainActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Keluar dari dashboard screen
finish();
}
});
}else{
// user is not logged in show login screen
Intent login = new Intent(getApplicationContext(), MainActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
}
}
And here's for ProfileActivity class :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
// Loading user Profile in Background Thread
new showUserProfile().execute();
}
///...
/**
* Background Async Task to Load user profile by making HTTP Request
* */
private class showUserProfile extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ProfileActivity.this);
pDialog.setMessage("Loading User Profile. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting user profile from url
* */
protected String doInBackground(String... args) {
//String name = name.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(profileURL, "GET", params);
/* UserFunctions userFunction = new UserFunctions();
if (params.length != 0)
return null;
JSONObject json = userFunction.userProfil(params[0]);
return json; */
// Check your log cat for JSON reponse
Log.d("User Profile: ", json.toString());
...
return null;
}
}
}
You are creating a new Intent in the Profile Activity.
You should actually use getIntent() to receive the intent the activity was called with.
That will return an intent object with your "name" extra.
EDIT: Actually, I can't tell precisely where you are trying to read the value sent from the Dashboard.
In ProfileActivity you should have
Intent intent = getIntent();
String name = intent.getStringExtra("name");
Then you can use the name from Dashboard in Profile.
Also look into implementing onNewIntent() for ProfileActivity.
EDIT: I edited your post to re-include where you call the AsyncTask. Notice your AsyncTask accepts a String parameter but you don't pass it one.
So do this in your ProfileActivity.onCreate():
Intent intent = getIntent();
String name = intent.getStringExtra("name");
new showUserProfile().execute(name);
Now in your doInBackground you should be able to get the name with args[0]
EDIT: Your AsyncTask should probably be:
private class showUserProfile extends AsyncTask<String, Void, Void>
Because you only accept the parameter, other don't use the progress or return values.
You are passing the extra properly, you just aren't retrieving it at all from your next activity.
Use Bundle var = getIntent().getExtras()
followed by
if(var != null){
myString = var.getString(KEY_NAME);
}

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

Android - How to accommodate a thread executing in AsyncTask doInBackground method

I am trying to query a web service using loopJ and during this operation I want to show the users a progress dialog. When the operation is complete, I want the progress dialog to dismiss and start a new activity intent.
I know AsyncTask is the way to go. On onPreExecute method I show the progress dialog. On doInBackground I am performing the network operation. And onPostExecute I am dismissing the dialog and starting a new activity intent.
My issue is doInBackground will perform loopJ networkcall asynchronously so onPostExecute will finish first before my network operation. If you look at my logs it will show:
"Starting new activity!"
"Fetched category services!"
rather
"Fetched category services!"
"Starting new activity!"
How do I accommodate an asynchronous task running doInBackground? Is there a way in onPostExecute to wait till my asynch loopJ operation is done?
public class FetchCategoriesServices extends AsyncTask<HITECategory, String, String>
{
private Category userSelectedCategory;
private ProgressDialog busyDialog;
#Override
protected void onPreExecute()
{
busyDialog = ProgressDialog.show(SearchActivity.this, getApplicationContext().getString(R.string.progressDialogTitle),
getApplicationContext().getString(R.string.progressDialogMessage));
}
#Override
protected String doInBackground(HITECategory... params)
{
userSelectedCategory = params[0];
String requestCategoryServiceURL = BASE_URL + "GetServices?CategoryID=" + userSelectedCategory.categoryID + "&ResponseType=JSON";
try
{
Client.get(requestCategoryServiceURL, new AsyncHttpResponseHandler()
{
#Override
public void onSuccess(String jsonResponse)
{
Gson gson = new Gson();
CategoryServicesListResponse Response = gson.fromJson(jsonResponse, CategoryServicesListResponse.class);
categoryServiceresults = Response.categoryServices;
Log.d(getString(R.string.DebugKey), "Fetched category services!");
}
});
}
catch (Exception e)
{
Log.d(getString(R.string.DebugKey), "Error connecting to service and fetching category services list");
}
return null;
}
#Override
protected void onPostExecute(String params)
{
busyDialog.dismiss();
Log.d(getString(R.string.DebugKey), "Starting new activity!");
Intent intent = new Intent(getApplicationContext(), CategoriesSearchActivity.class);
startActivity(intent);
}
}
Just put the code in onPostExecute into onSuccess method:
Client.get(requestCategoryServiceURL, new AsyncHttpResponseHandler()
{
#Override
public void onSuccess(String jsonResponse)
{
Gson gson = new Gson();
CategoryServicesListResponse Response = gson.fromJson(jsonResponse, CategoryServicesListResponse.class);
categoryServiceresults = Response.categoryServices;
Log.d(getString(R.string.DebugKey), "Fetched category services!");
youractivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
busyDialog.dismiss();
Log.d(getString(R.string.DebugKey),
"Starting new activity!");
Intent intent = new Intent(getApplicationContext(),
CategoriesSearchActivity.class);
youractivity.this.startActivity(intent);
}
});
}
});

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