How to call notifyDataSetChanged() on ArrayList view? - java

This is the ArrayList page that opens as a result page after update and save. I guess I would need to somehow refresh so that it reflects the changes on the UI. I've tried to call notifyDataSetChanged() but no luck with my level of experience. Could someone kindly show how to implement it please?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_requests);
requestsList = new ArrayList<HashMap<String, String>>();
new LoadAllRequests().execute();
ListView list = getListView();
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String request_id = ((TextView) view.findViewById(R.id.request_id)).getText().toString();
Intent in = new Intent(getApplicationContext(),
ViewRequestActivity.class);
in.putExtra(TAG_ID, request_id);
startActivityForResult(in, 100);
}
});
}
// Response from ViewRequestActivity when delete a request reload this page again
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
class LoadAllRequests extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_all_requests, "GET", params);
Log.d("All Requests: ", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
requests = json.getJSONArray(TAG_REQUESTS);
for (int i = 0; i < requests.length(); i++) {
JSONObject c = requests.getJSONObject(i);
String request_id = c.getString(TAG_ID);
String request_title = c.getString(TAG_TITLE);
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, request_id);
map.put(TAG_TITLE, request_title);
requestsList.add(map);
}
} else {
Intent i = new Intent(getApplicationContext(),
NewRequestActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}

You need to create an adapter for your ListView. The adapter is what feeds data to it for displaying. I would recommend you reading through this tutorial:
http://www.vogella.com/articles/AndroidListView/article.html
So once you have created your adapter and then called lv.setAdapter(<adapter>), you can then call <adapter>.notifyDataSetChanged(). This will tell the adapter that it needs to refresh itself.

You can use notifyDataSetChanged() method for your adapter.Wherever you want to update your listview you can use in following manner.
adapter.notifyDataSetChanged();

Related

How to send data from class to class in async?

I need to know how to do that?
I have two views
ActivityMain.java
FilmActivity
In MainActivity, I created an intent to get some information from the second view:
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
CustomGridviewAdapter customGridviewAdapter = new CustomGridviewAdapter(filmList, getApplicationContext());
simpleGrid.setAdapter(customGridviewAdapter);
simpleGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), FilmActivity.class);
intent.putExtra("FilmBoster", filmList.get(position).getBackdrop_path())
.putExtra("FilmImage", filmList.get(position).getPoster_path())
.putExtra("FilmName", filmList.get(position).getTitle())
.putExtra("FilmDate", filmList.get(position).getRelease_date())
.putExtra("FilmDisc", filmList.get(position).getOverview())
.putExtra("isFavFilm", filmList.get(position).getIsLiked());
startActivityForResult(intent, 2);
}
});
}
Second view :
private void sendDataToMainActivity(String isPressed) {
Intent intent = new Intent();
intent.putExtra("isPressed" , isPressed);
setResult(1 , intent);
finish();
}
I have used AsyncTask In MainActivity. The second activity sent the data in onActivityResult but ( onActivityResult ) execute After AsyncTask and in AsyncTask, I set some data on DB. So that the data that returned from the Second Activity is equal to null.
Some codes to help
#NonNull
private String convertToString(InputStream in) {
String res = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sd = new StringBuilder();
try {
while ((res = reader.readLine()) != null) {
sd.append(res).append("/n");
}
} catch (IOException e) {
e.printStackTrace();
}
parseString(sd.toString());
db.userDao().updateFilmList(filmList);
return sd.toString();
}
private void parseString(String json) {
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject filmObject = jsonArray.getJSONObject(i);
Film film = new Film(filmObject.getString("title")
,filmObject.getString("overview")
, filmObject.getString("poster_path")
, filmObject.getString("release_date")
,db.userDao().getIsFave());
filmList.add(film);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
This is two methods inside AsyncTask that save data to db
What should I do if I want the data return on AsyncTask and set it on DB?
Do the following up in your onCreate or onResume methods in your MainActivity class:
// filmList should be an empty array at this point
CustomGridviewAdapter customGridviewAdapter = new CustomGridviewAdapter(filmList, getApplicationContext());
simpleGrid.setAdapter(customGridviewAdapter);
simpleGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), FilmActivity.class);
intent.putExtra("FilmBoster", filmList.get(position).getBackdrop_path())
.putExtra("FilmImage", filmList.get(position).getPoster_path())
.putExtra("FilmName", filmList.get(position).getTitle())
.putExtra("FilmDate", filmList.get(position).getRelease_date())
.putExtra("FilmDisc", filmList.get(position).getOverview())
.putExtra("isFavFilm", filmList.get(position).getIsLiked());
startActivityForResult(intent, 2);
}
});
Then, in your postExecute method, you just need to do this (assuming you have repopulated your filmList in the Async Task):
CustomGridviewAdapter customGridviewAdapter = new CustomGridviewAdapter(filmList, getApplicationContext());
simpleGrid.setAdapter(customGridviewAdapter);
The onItemClicked handler will send the item clicked on to the FilmActivity.java class activity. In the onCreate of that activity, you need to read the data passed to it from the MainActivity:
public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
setContentView(R.layout.film_activity_layout);
FilmName = (String) getIntent().getExtra("FilmName");
...
}
You need to show the onActivityResult code from the MainActivity
Do you have to use Async Task? I would suggest to use RxJava instead.
However, you can create a class that extends AsyncTask and send the Context in the constructor in order to setResult and finish the current activity in onPostExecute.
Example : https://stackoverflow.com/a/16921076/12009871

Activity leaked :android.view.WindowLeakedActivity com.example.androidhive.AllProductsActivity has leaked window DecorView#bf6bd49[]

This is my MainScreenActivity.java code:
public class MainScreenActivity extends Activity{
Button btnViewProducts;
Button btnNewProduct;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_screen);
// Buttons
btnViewProducts = (Button) findViewById(R.id.btnViewProducts);
btnNewProduct = (Button) findViewById(R.id.btnCreateProduct);
// view products click event
btnViewProducts.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Launching All products Activity
Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
startActivity(i);
}
});
// view products click event
btnNewProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Launching create new product activity
Intent i = new Intent(getApplicationContext(), NewProductActivity.class);
startActivity(i);
}
});
}
My AllProductsActivity.java:
public class AllProductsActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "http://127.0.0.1/android_connect2/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_products);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON response
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllProductsActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
Below is my logcat:
11-25 13:59:59.941 10468-10468/com.example.androidhive E/WindowManager: android.view.WindowLeaked: Activity com.example.androidhive.AllProductsActivity has leaked window DecorView#bf6bd49[] that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:417)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:331)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
at android.app.Dialog.show(Dialog.java:316)
at com.example.androidhive.AllProductsActivity$LoadAllProducts.onPreExecute(AllProductsActivity.java:117)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:613)
at android.os.AsyncTask.execute(AsyncTask.java:560)
at com.example.androidhive.AllProductsActivity.onCreate(AllProductsActivity.java:57)
at android.app.Activity.performCreate(Activity.java:6664)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
I'm just a beginner and I have no idea what is causing the error. I have searched the site for solutions but it seems that this error is code specific. Any help is appreciated.
This happen because you have not initialize your ProgressDialog properly or you do not close your progress dialog properly. Make sure that in onPause() you call pDialog.dismiss(); And also initialize in this way.
Make object of Context and initialize it in onCreate(); as mContext=YourActivity.this
pDialog= ProgressDialog.show(mContext);
Problem is in do in background, check your else condition you are starting another activity from there so just put pDialog.dismiss(); before you start another activity
Reason behind this crash is you dialog is still showing and you are changing Activity so its showing WindowLeaked error
As you doInBackground will not allow to hide dialog you can hide it in onPause() method it will also work

RecyclerView passing data via Intent extras

So I'm trying to pass some data via Intent extras to the second activity. This code worked fine with ListView, but now when I switched to RecyclerView it doesn't show any text, text area is blank.
Here's the code: (starting in onBindViewHolder())
holder.container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
passData();
}
});
}
private void passData() {
Todo item = new Todo();
Intent i = new Intent(c, Details.class);
i.putExtra("nazivTodoa", item.getTitle());
i.putExtra("datumTodoa", item.getRecordDate());
i.putExtra("idTodoa", item.getItemId());
c.startActivity(i);
}
And this is how I get in in second activity:
Bundle extras = getIntent().getExtras();
String naslov = extras.getString("nazivTodoa");
String datum = extras.getString("datumTodoa");
textViewNazivTodoaDetails.setText(naslov);
textViewDatumTodoaDetails.setText(datum);
What am I doing wrong?
What you are doing wrong, is you are not getting the current object that is clicked on. You do that by getting your object from the arraylist you use in your adapter. Do it like that:
Arraylist<Item> yourlist = new Arraylist();
#Override
public void onClick(View v) {
// position = pass the current position of the object you want
passData(int position);
}
});
}
private void passData(int position) {
Todo item = new Todo();
Intent i = new Intent(c, Details.class);
i.putExtra("nazivTodoa", yourlist.get(position).getTitle());
i.putExtra("datumTodoa", yourlist.get(position).item.getRecordDate());
i.putExtra("idTodoa", yourlist.get(position).item.getItemId());
c.startActivity(i);
}
Like dymmeh said, you need to pass the item in the list to the new activity. You are currently passing a newly created empty object.
Instead of
Todo item = new Todo();
Intent i = new Intent(c, Details.class);
i.putExtra("nazivTodoa", item.getTitle());
i.putExtra("datumTodoa", item.getRecordDate());
i.putExtra("idTodoa", item.getItemId());
You should have
Todo item = listData.get(itemPosition);
Intent i = new Intent(c, Details.class);
i.putExtra("nazivTodoa", item.getTitle());
i.putExtra("datumTodoa", item.getRecordDate());
i.putExtra("idTodoa", item.getItemId());

How i have to get the id in JSON after click the button and want to send that id again in post method

Actually i am parsing in json id,content,title,count.But i dont want to display id,but after click the button it has to get the id value and i have to send that id to the server side.
this is my json parsing values:
{"post":[{"id":170,"title":"Exams","content":"pass","count":3},{"id":169,"title":"Exams","content":"pass","count":3}, From here i want to get the id after click the pray button and want to send that id in post method also.
Activity.java
public class MainActivity extends Activity implements FetchDataListener,OnClickListener
{
private static final int ACTIVITY_CREATE=0;
private ProgressDialog dialog;
ListView lv;
private List<Application> items;
private Button btnGetSelected;
private Button praycount;
public int count;
private String stringVal;
private TextView value;
//private ProjectsDbAdapter mDbHelper;
//private SimpleCursorAdapter dataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item);
//mDbHelper = new ProjectsDbAdapter(this);
//mDbHelper.open();
//fillData();
//registerForContextMenu(getListView());
praycount = (Button) findViewById(R.id.pray);
praycount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count++;
stringVal = Integer.toString(count);
value.setText(stringVal);
if(value.getText().toString().length()<1){
// out of range
//Toast.makeText(this, "please enter something", Toast.LENGTH_LONG).show();
}else{
praydata(stringVal);
}
}});
lv =(ListView)findViewById(R.id.list);
btnGetSelected = (Button) findViewById(R.id.btnget);
btnGetSelected.setOnClickListener(this);
initView();
}
public void praydata(String valueIWantToSend) {
// Create a new HttpClient and Post Header.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.ginfy.com/api/v1/posts/id.json");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("post[id]", valueIWantToSend));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//httppost.addHeader("Authorization","Basic "+authorization);
//httppost.addHeader("Content-Type","application/x-www-form-urlencoded");
httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
httppost.setHeader("Accept", "application/json");
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
private void initView()
{
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading...");
String url = "http://www.ginfy.com/api/v1/posts.json";
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
createProject();
return super.onMenuItemSelected(featureId, item);
}
private void createProject() {
Intent i = new Intent(this, AddPrayerActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
initView();
}
#Override
public void onFetchComplete(List<Application> data)
{
this.items = data;
// dismiss the progress dialog
if ( dialog != null )
dialog.dismiss();
// create new adapter
ApplicationAdapter adapter = new ApplicationAdapter(this, data);
// set the adapter to list
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
CheckBox chk = (CheckBox) view.findViewById(R.id.checkbox);
Application bean = items.get(position);
if (bean.isSelected()) {
bean.setSelected(false);
chk.setChecked(false);
} else {
bean.setSelected(true);
chk.setChecked(true);
}
}
});
}
// Toast is here...
private void showToast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onFetchFailure(String msg)
{
// dismiss the progress dialog
if ( dialog != null )
dialog.dismiss();
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
#Override
public void onClick(View v) {
StringBuffer sb = new StringBuffer();
// Retrive Data from list
for (Application bean : items) {
if (bean.isSelected()) {
sb.append("Title:");
sb.append(Html.fromHtml(bean.getTitle()));
sb.append(",Content:");
sb.append(Html.fromHtml(bean.getContent()));
sb.append("\n");
}
}
showAlertView(sb.toString().trim());
}
#SuppressWarnings("deprecation")
private void showAlertView(String str) {
AlertDialog alert = new AlertDialog.Builder(this).create();
final String strContactList = str.substring(0, str.length());
if (TextUtils.isEmpty(str)) {
alert.setTitle("Not Selected");
alert.setMessage("No One is Seleceted!!!");
} else {
// Remove , end of the name
alert.setTitle("Selected");
alert.setMessage(strContactList);
}
alert.setButton("sms", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//sendSMS();
/*Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", strContactList);
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);
finish();*/
Intent intent1=new Intent(MainActivity.this,SendSMSActivity.class);
//Log.d("test","strContactList: "+strContactList);
intent1.putExtra("firstKeyName", strContactList);
startActivity(intent1);
}
});
Actually want i want that i want to get an id fronm one json its already i mention,after click the button selection id i want to send again in another json url as post method.
for this you can use javascript to read the id of the particular property selected and using that you can display what ever details you want.

onActivityResult() is not calling from Activity

I'm able to edit & save data from one Activity(EditActivity.java), but the updated data doesn't display(or carried over) to the next Activity(ViewActivity.java) when click Save button. I can see the changes on the EditText fields if go back to the EditActivity page.
EditActivity.java
btnSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// starting background task to update request
new SaveRequestDetails().execute();
}
});
class SaveRequestDetails extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
// getting updated data from EditTexts
String request_title = txtTitle.getText().toString();
String request_date = txtSdate.getText().toString();
String reqEndDate = txtEdate.getText().toString();
String hours = txtHours.getText().toString();
String reason = txtReason.getText().toString();
String explanation = txtExp.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(TAG_ID, request_id));
params.add(new BasicNameValuePair(TAG_TITLE, request_title));
params.add(new BasicNameValuePair(TAG_SDATE, request_date));
params.add(new BasicNameValuePair(TAG_EDATE, reqEndDate));
params.add(new BasicNameValuePair(TAG_HOURS, hours));
params.add(new BasicNameValuePair(TAG_REASON, reason));
params.add(new BasicNameValuePair(TAG_EXP, explanation));
JSONObject json = jsonParser.makeHttpRequest(url_update_request,
"POST", params);
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Intent i = getIntent();
// send result code 100 to notify about request update
setResult(100, i);
finish();
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
ViewActivity.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_request);
Intent i = getIntent();
// getting request id (rid) from intent
request_id = i.getStringExtra(TAG_ID);
// Getting complete request details in background thread
new GetRequestDetails().execute();
btnEdit = (Button) findViewById(R.id.btnEdit);
btnEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Starting new intent
Intent in = new Intent(getApplicationContext(), EditActivity.class);
// sending rid to next activity
in.putExtra(TAG_ID, request_id);
startActivity(in);
}
});
}
// Response from Edit Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted request
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
Your headline says that, that onActivityResult() does not get called.
Use startActivityForResult(in, 55) instead of startActivity(in)
//EDIT:
By the way, checking the result code should by done using the RESULT_OK / RESULT_CANCELED constants. You might also consider checking the request code (in my example code it would be 55)

Categories

Resources