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());
Related
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
I have a json file and I want to check this json every minute because my json changes every minute.
I can parse json from an url in this way;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute("http://www.url.com/json1.json");
}
});
}
class ReadJSON2 extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
#Override
protected void onPostExecute(String content) {
try {
JSONObject jsonObject = new JSONObject(content);
JSONArray jsonArray = jsonObject.getJSONArray("level");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
JSONArray server = c.getJSONArray("server");
for(int j=0; j<server.length(); j++){
JSONObject serverObject = server.getJSONObject(j);
String name = serverObject.getString("name");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
How can I check this json every minute?
I did everything, but I didn't it.
Thank you for your help.
Use listview.invalidateViews(); or adapter.notifyDataSetchanged(); method in onPostExecute method after parsing your json.
This method works if some of the contents have been changes/added/removed in the list that is attached to the adapter.
So whenever you parse your data . make sure the object of adapter and the List/JsonArray remain same. Means dont initialize it every time on web service result. Just use it like this -> list.add(some data); and jsonArray.put(some data);
Let me know if i misunderstood.
We can use TimerTask to solve this problem:
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
//use a handler to run a toast that shows the current timestamp
handler.post(new Runnable() {
public void run() {
new ReadJSON().execute("http://www.url.com/json1.json");
}
});
}
};
public void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
//schedule the timer, after the first 0ms the TimerTask will run every 1m
timer.schedule(timerTask, 0, 60 * 1000); //
}
An on ur postExe, after parse JSON, u should check Adapter here, if it's was empty for first time, you set adapter by this json, and if it's already has data, please call adapter.notifyDataSetChanged()
I have an activity that creates a list based on a list of series values returned by an http request. If the list includes a list of places, I call the next activity and pass some values through intents. However, if the response does not include a list of places, I need to repopulate my activity with a new list of series values, but I'm not sure how to call the same activity within the activity I'm already in. My attempt is below.
EDIT: the goal of refreshing the activity is to make an https request with new parameters in the url. I tried just recalling the http request earlier, but had no luck
protected void onPostExecute(JSONObject result){
ArrayList<String> modelNames = new ArrayList<>();
Log.d("JSON RESPONSE", result.toString());
final ArrayList<JSONObject> modelsObjectList = new ArrayList<>();
try {
JSONObject info = result.getJSONObject("info");
JSONArray models = info.getJSONArray("models");
for(int i = 0; i < models.length(); i++){
modelsObjectList.add(models.getJSONObject(i));
}
for(int i = 0; i < modelsObjectList.size(); i++){
modelNames.add(modelsObjectList.get(i).getString("name"));
}
} catch(JSONException e ){
Log.d("JSONEXCEPTION", e.getMessage().toString());
}
//TODO found problem, model names for whatever reason is passing in the names from previous activity
Log.d("MODEL NAMES", modelNames.toString());
Toast.makeText(AfterDestinationActivity.this, modelNames.toString(), Toast.LENGTH_LONG).show();
mList = (ListView) findViewById(android.R.id.list);
CustomMainAdapter mainAdapter = new CustomMainAdapter(AfterDestinationActivity.this, modelNames);
mList.setAdapter(mainAdapter);
setProgressBarIndeterminateVisibility(false);
mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
String name;
Long id;
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
JSONObject passingObject = modelsObjectList.get(position);
ArrayList<String> nextPlacesList = new ArrayList<>();
Log.d("AD OBJECT PRESSED ON", passingObject.toString());
//TODO found issues with debugging
try {
JSONArray places;
JSONArray series = passingObject.getJSONArray("series");
name = passingObject.getString("name");
id = passingObject.getLong("id");
Log.d("NEXT ACTIVITY NAME", name);
System.out.println("NEXT ACTIVITY ID " + id);
Log.d("NEXT SERIES LIST", nextPlacesList.toString());
//if there are no places, launch http request again for series
if(passingObject.optJSONArray("places") == null){
ArrayList<String> sameSeries = new ArrayList();
System.out.println("WENT INTO FOR LOOP");
for(int i = 0; i < series.length(); i++){
sameSeries.add(series.getString(i));
Log.d("AD FOR LOOP SERIES", series.getString(i));
}
Intent refreshActivity = new Intent(AfterDestinationActivity.this, AfterDestinationActivity.class);
refreshActivity.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
refreshActivity.putExtra("id", id);
refreshActivity.putExtra("name", name);
refreshActivity.putExtra("placesList", nextPlacesList);
Log.v("RESTARTING ACTIVIY", "activity restating");
startActivity(refreshActivity);
}
} catch(JSONException e){
Log.d("JSONEXCEPTION", "IN THERE " + e.getMessage());
}
Intent intent = new Intent(AfterDestinationActivity.this, PlacesListActivity.class);
intent.putExtra("id", id);
intent.putExtra("name", name);
intent.putExtra("placesList", nextPlacesList);
startActivity(intent);
}
});
}
Simply use this,
add this in your manifest,
<activity android:name=".StartActivity" android:label="#string/app_name"
android:clearTaskOnLaunch="true">
</activity>
From JAVA code use this,
Intent refreshActivity = new Intent(AfterDestinationActivity.this, AfterDestinationActivity.class);
refreshActivity.putExtra("id", id);
refreshActivity.putExtra("name", name);
refreshActivity.putExtra("placesList", nextPlacesList);
Log.v("RESTARTING ACTIVIY", "activity restarting");
startActivity(refreshActivity);
You don't need to call the same activity. Just update the corresponding views with the new values in your activity.
I would access it via the "this pointer" or an interface:
EDIT
MyActivity extends Activity implements IUpdateListener
{
public void onCreate(Bundle onSaveInstanceState)
{
//code
}
#Override
void onUpdate(Result result)
{
//update data or do other stuff - like start another activity or populate urs.
}
}
Next The AsynTask:
MyAsyncTask extends AsyncTask<Void, Void, Result>
{
private IUpdateListener listener;
public MyAsyncTask(IUpdateListener listener)
{
this.listener = listener;
}
Result doInBackground(Void.. voids)
{
//http request and parse - an object Result
return result data;
}
void onPostExecute(Result result)
{
if(result!=null) - or other operation u want
{
listener.OnUpdate(result) - or other stuff you want.
}
}
Next the interface:
interface IOnUpdateListener
{
onUpdate(Result result);
}
"this pointer":
How can I access my Activity's instance variables from within an AlertDialog's onClickListener?
I hope I was clear enough.
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
I have a String type array. I want to show each element in a TextView after a little time slice that means after certain time the element of array is showing in a TextView again and again. So I am using timer, but it is showing only last element of array. Please solve my problem as soon as possible.
protected void onPostExecute(Void result) {
try {
super.onPostExecute(result);
listAdapter = new ExpandableListAdapter(getActivity(), listDataHeader, headerChild, expListView);
expListView.setAdapter(listAdapter);
int j=0, k=1;
if (prog.isShowing()) {
prog.dismiss();
expListView.setBackgroundColor(0xFFFFFFFF);
String af="";
String cf="";
for(int i=0; i<breakstore2.length; i++){
cf=breakstore2[j];
af= breakstore2[k];
new Handler().postDelayed(new Runnable() {
public void run() {
marquee.setText("Breaking News :" + af);
marquee.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent mainIntent = new Intent(getActivity(),h_nextpage2.class);
mainIntent.putExtra("listitem", cf);
startActivity(mainIntent);
}
});
}
}, DISPALY_LENGTH);
j=j+2;
k=k+2;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
The method is updating the UI faster than you wanted...what you can do is that you can create an IntentService and send that service the data that need to be put on your screen.
Create Messenger in your main activity where you need to update the UI and also create an Handler in the same. And from your AsyncTask post the updates to the intentService in that you can delay the updation by sleeping the intentServices' thread and then sending a message to the messenger on the main activity containing the data which you need to show (in your case breaking news) which in turn will do the updation for you.