viewPager.setCurrentItem() doesn't work in onActivityResult - android

I have implemented FragmentStatePagerSupport. I have 142 pages. I have also an activity that is MyListActivity and has ListView. When I click ListView item, it returns a page number. I want to use this page number for viewPager current page. viewPager.setCurrentItem() doesn't work in onActivityResult.
Here is how I call startActivityForResult:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu1:
Intent intent = new Intent(this, MyListActivity.class);
startActivityForResult(icindekiler, 0);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
And here is the listView of MyListActivity:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ListViewContent selectedItem = (ListViewContent) parent.getItemAtPosition(position);
int pageNo = book.getSpine().getResourceIndex(selectedItem.getResource().getHref());
Intent data = new Intent();
data.putExtra("PageNo", pageNo); // pageNo: 0 or 1 or 2 or ... or 142
setResult(0, data);
finish();
}
});
onActivityResult method in FragmentPageStateSupport activity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == 0) {
if (data.hasExtra("PageNo")) {
pageNo = data.getExtras().getInt("PageNo");
Toast.makeText(getBaseContext(), "pageNo is " + pageNo, Toast.LENGTH_SHORT).show();
viewPager.setCurrentItem(pageNo);
}
}
}
For example pageNo is 11, Toast says "pageNo is 11" but viewPager doesn't change. When I use debugging in Android Studio, application runs Looper.java. I try viewPager.setCurrentItem(11) on different method (for example button click), this time it is working.

Related

Check whether the check box is checked

Activity A has a listView , Activity B has a checkBox and save button.
When save button in B is clicked, it will return to Activity A. When the list in Activity A is pressed, how to show the check box is checked in Activity B if it is checked before return to A ?
Activity B
if(getIntent().getExtras()!=null) // when Activity A list is pressed
{
final String from = getIntent().getStringExtra("from");
travelFrom.setText(from);
// how to show check box is checked ?
}
save.setOnClickListener(new View.OnClickListener() { // if save button clicked, return from and outstation to A
#Override
public void onClick(View v) {
String from=travelFrom.getText().toString();
returnIntent.putExtra("from", from);
if(checkbox.isChecked()) {
returnIntent.putExtra("outstation", checkbox.getText().toString());
}
}
});
Activity A
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { // if listView is clicked
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
mClickedPosition = position;
Object o = listview.getItemAtPosition(position);
SearchResults fullObject = (SearchResults) o;
String from=fullObject.getFrom();
Intent i = new Intent(getApplication(),B.class);
i.putExtra("from",from);
startActivityForResult(i, PROJECT_REQUEST_CODE);
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { // receive from Activity B and populate ListView A
if (resultCode == RESULT_OK) {
if (requestCode == PROJECT_REQUEST_CODE) {
from=data.getStringExtra("from");
check=data.getStringExtra("outstation");
objMyCustomBaseAdapter.addNewItem(from,check); // save from and "outstation" into MySQL
}
}
}
When I press the list in A to B, the check box always not checked. How to make it check ?
Do something like implementing setOnclicklistner for checkbox. and assume an int variable to be zero. and when ever we click the checkbox increase the number by 1 every time. When we are moving from one activity to another send the data of int variable to Activity B. check Activity check the condition int variable as variable%2 if the value is equal to 1 the check box is checked. else it is not.
Assuming you have some object with this...
class MyData {
private boolean check;
public boolean getCheck() { return check; }
}
Here is some rough pseudo-code to demonstrate the concept, so not copy-paste worthy
Activity A - Pass in the boolean value that you want to the next activity
class ActivityA {
private ListView listView
onCreate() {
listView = (ListView) findViewById(R.id.list);
ArrayAdapter adapter = new ArrayAdapter();
listView.setAdapter(adapter);
listView.setOnItemClickListener( new ItemClickListener() {
onClick(int position) {
MyData listObject = adapter.getItem(position);
boolean checked = listObject.getCheck();
Intent i = new Intent(ActivityA.this, ActivityB.class);
i.putExtra("checkTheBox", check);
startActivity(i);
}
});
}
}
Activity B - Get the value out of the intent and set the checkbox to checked
class ActivityB {
private Checkbox checkbox;
onCreate() {
checkbox = (Checkbox) findViewById(R.id.checkbox);
Bundle extras = getIntent().getExtras();
if (extras != null) {
checkbox.setChecked(extras.getBooleanExtra("checkTheBox"));
}
}
}
You have to save the checked status for the selected list item when returning back from Activity B to Activity A.
In order to do that, you can simply store information in Activity A for the currently selected list item.
(for example TreeMap<View, Boolean> - item-> isSelected)
Then in onActivityResult you can set if there has been a check or not for the last selected item. When selecting again, before you create the intent you can check if this item has already been selected.
To know ActivityA ListItem is checked in ActivityB (ie CheckBox) or not. Check this below code hope this helps
ActivityA stuff
int selectedPosition;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//your UI setup and findViewById stuff
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedPosition = position;
startActivityForResult(activityBIntent, REQ_CODE);
}
});
}
int REQ_CODE = 7;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQ_CODE)
if (resultCode == RESULT_OK) {
adapter.changeStatus(selectedPosition, true);//update adapter
} else {
//checkbox not checked
adapter.changeStatus(selectedPosition, false);//update adapter
}
}
ActivityB stuff
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//your UI stuff
setResult(RESULT_CANCELED);//default
//check box setup and save button onclick listener
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.save_button){
if (checkBox.isChecked())
setResult(RESULT_OK);
else
setResult(RESULT_CANCELED);//default
finish();//finish ActivityB and take the result to ActivityA
}
}

I can't update an item on my list view using item id.

I have a list view with data base and when i click on an item on the list i want to move to edit page activity in order to update the item.
What am i doing wrong?
There is my code:
//by pressing a short press on any item the user moved to the edit page in order to edit his note
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
intent=new Intent(MainActivity.this,Edit_Note.class);
intent.putExtra("item_id", list.get(position).getId());
intent.putExtra("position", position);
intent.putExtra("item_title", list.get(position).getTitle().toString());
intent.putExtra("item_content", list.get(position).getContent().toString());
startActivityForResult(intent, FLAG_FOR_EDITING);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==ADD_FLAG && resultCode==RESULT_OK ){
//i am getting the information (title and content) from the edit note activity
String the_title=data.getStringExtra("user_title");
String the_content=data.getStringExtra("user_content");
//the information is added to the database
database.addNote(the_title,the_content);
}
else if(requestCode==ADD_FLAG && resultCode==RESULT_CANCELED){
Toast.makeText(MainActivity.this, "no changes have been made", Toast.LENGTH_LONG).show();
}
else if
(requestCode==FLAG_FOR_EDITING && resultCode==RESULT_OK){
int position_from_edit=data.getIntExtra("position", -2);
String title_editing=data.getStringExtra("user_title");
String content_editing=data.getStringExtra("user_content");
database.editNote("position_from_edit", title_editing, content_editing);
}
edit_title=(EditText)findViewById(R.id.edit_title);
edit_content=(EditText)findViewById(R.id.edit_content);
ImageButton save=(ImageButton)findViewById(R.id.save);
ImageButton clear=(ImageButton)findViewById(R.id.clear);
String received_title=intent.getStringExtra("item_title");
String received_content=intent.getStringExtra("item_content");
item_id=String.valueOf(intent.getIntExtra("item_id", -1));
edit_title.setText(received_title);
edit_content.setText(received_content);
//by pressing the save button, the information is sending to the main activity page
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
//i am receiving the text that the user entered to the title and to the content fields
entered_title=edit_title.getText().toString();
entered_content=edit_content.getText().toString();
intent.putExtra("position", item_id);
intent.putExtra("user_title", entered_title);
intent.putExtra("user_content", entered_content);
setResult(RESULT_OK, intent);
finish();
}
}
When you want to pass so much data through an activity, it is best to bind that data into a bundle. You should store all your data into a bundle and then bind it to the intent and then pass in the activity.
Bundle value=new Bundle;
value.putString("item_title", list.get(position).getTitle().toString());
value.putString("item_content", list.get(position).getContent().toString());
value.putInt("item_id", list.get(position).getId());
value.putInt("position", position);
intent.putExtras(value);
startActivityForResult(intent,0);

Calling Activity from Fragment then return to Fragment

I have an app that has a few tabs. These tabs are all fragments. On the first tab fragment, I have a text view and a button, which I press on to call an activity.
This activity displays a list of items, car names.
I want to be able to click on a car in the list and return back to the calling fragment and update the text view with the car name I selected.
Can anyone help me out with this?
startActivityForResult() is probably what you're looking for. So a quick example (making super-basic assumptions about your data structure -- substitute as required) would be to make your fragment override onActivityResult(), define a request code, and then start the activity using that request code:
// Arbitrary value
private static final int REQUEST_CODE_GET_CAR = 1;
private void startCarActivity() {
Intent i = new Intent(getActivity(), CarActivity.class);
startActivityForResult(i, REQUEST_CODE_GET_CAR);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// If the activity result was received from the "Get Car" request
if (REQUEST_CODE_GET_CAR == requestCode) {
// If the activity confirmed a selection
if (Activity.RESULT_OK == resultCode) {
// Grab whatever data identifies that car that was sent in
// setResult(int, Intent)
final int carId = data.getIntExtra(CarActivity.EXTRA_CAR_ID, -1);
} else {
// You can handle a case where no selection was made if you want
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
Then, in the CarActivity, wherever you set a click listener for your list, set the result and pass back whatever data you need in an Intent:
public static final String EXTRA_CAR_ID = "com.my.application.CarActivity.EXTRA_CAR_ID";
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Assuming you have an adapter that returns a Car object
Car car = (Car) parent.getItemAtPosition(position);
Intent i = new Intent();
// Throw in some identifier
i.putExtra(EXTRA_CAR_ID, car.getId());
// Set the result with this data, and finish the activity
setResult(RESULT_OK, i);
finish();
}
call startActivityForResult(theIntent, 1);
In the activity started, once the user selects a car, make sure to put the car in an intent and set the result of the activity to that intent
Intent returnIntent = new Intent();
returnIntent.putExtra("result", theCar);
setResult(RESULT_OK, returnIntent);
finish();
Then, in your fragment, implement onActivityResult
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
String result = data.getStringExtra("result");
}
if (resultCode == RESULT_CANCELED) {
//Write your code if there's no result
}
}
} //onActivityResult
Make Sure to override onActivityResult() in the fragment's hosting activity too, and call the super
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
This is because the parent activity hijacks the onActivityResult method, and if you don't call super() then it wont get passed to the fragment to handle it

Android: how to make the items from listview opens to diff. activity/intent

I created a listview and would like to know how to have each diff. item open diff. activity/intent
example: In listview
-start trip (it will grab the gps location data send that to the server right away and confirm its been sent)
-Clock in (it will grab the time/date data and send that to the server right away and confirm its been sent)
-Customer Svc (intent to the barcode scanner and return result no display and send result data to the server
right away)
-Independent Inspection (intent to the barcode scanner and return result no display and send result data to the
server right away)
-Pick Up (intent to the barcode scanner and return result no display and send result data to the server right
away)
-Log out (it will ask for password to complete a log out)
Im using project 2.2 with sdk 3 will be using the 1.5 firmware device motorola i1. I imported the zxing barcode
scanner "android integrate" to the project which should open the barcode scanner app seperately. .I am using eclipse. One last thing I am getting error at resultTxt and would like to know how to fix that problem?
Thanks
Merrill
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="#+id/selection"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<ListView android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawSelectorOnTop="false"/>
</LinearLayout>
Customer.java
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class Customer extends ListActivity
{
TextView selection;
String[] items = { "Start Trip", "Clock in", "Customer Svc",
"Independent Inspection", "Pick Up", "Log Out" };
#Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
setListAdapter(new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1, items));
selection = (TextView) findViewById(R.id.selection);
}
public void onListItemClick(ListView parent, View v, int position, long id)
{
Intent intent = new Intent("com.company.merrill.IntentIntegrator");
intent.setPackage("com.company.merrill");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
}
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if (requestCode == 0)
{
if (resultCode == RESULT_OK)
{
// contents contains whatever the code was
String contents = intent.getStringExtra("SCAN_RESULT");
// Format contains the type of code i.e. UPC, EAN, QRCode etc...
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
// Handle successful scan. In this example
// I just put the results into the TextView
resultsTxt.setText(format + "\n" + contents);
}
else if (resultCode == RESULT_CANCELED)
{
// Handle cancel. If the user presses 'back'
// before a code is scanned.
resultsTxt.setText("Canceled");
}
}
}
}
You can start different activities based on the position in the ListView of the item you just clicked:
private static final int ACTIVITY_0 = 0;
private static final int ACTIVITY_1 = 1;
private static final int ACTIVITY_2 = 2;
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
final Intent intent = new Intent();
// Set up different intents based on the item clicked:
switch (position)
{
case ACTIVITY_0:
intent.setClass(this, com.company.merrill.IntentIntegrator.class);
break;
case ACTIVITY_1:
intent.setClass(this, com.company.merrill.SecondActivity.class);
break;
case ACTIVITY_2:
intent.setClass(this, com.company.merrill.ThirdActivity.class);
break;
default:
break;
}
// Pass the item position as the requestCode parameter, so on the `Activity`'s
// return you can examine it, and determine which activity were you in prior.
startActivityForResult(intent, position);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_OK)
{
// Perform different actions based on from which activity is
// the application returning:
switch (requestCode)
{
case ACTIVITY_0:
// contents contains whatever the code was
String contents = intent.getStringExtra("SCAN_RESULT");
// Format contains the type of code i.e. UPC, EAN, QRCode etc...
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
// Handle successful scan. In this example
// I just put the results into the TextView
resultsTxt.setText(format + "\n" + contents);
break;
case ACTIVITY_1:
// TODO: handle the return of the SecondActivity
break;
case ACTIVITY_2:
// TODO: handle the return of the ThirdActivity
break;
default:
break;
}
}
else if (resultCode == RESULT_CANCELED)
{
// Handle cancel. If the user presses 'back'
// before a code is scanned.
resultsTxt.setText("Canceled");
}
}
Update
For a bit more elegant result, you can create your own type of list item data:
CustomerListItem.java
public class CustomerListItem
{
private String label;
private Class<?> activity;
/**
* #param label
* #param activity
*/
public CustomerListItem(String label, Class<?> activity)
{
super();
this.label = label;
this.activity = activity;
}
/**
* #return the label
*/
public String getLabel()
{
return label;
}
/**
* #param label the label to set
*/
public void setLabel(String label)
{
this.label = label;
}
/**
* #return the activity
*/
public Class<?> getActivity()
{
return activity;
}
/**
* #param activity the activity to set
*/
public void setActivity(Class<Activity> activity)
{
this.activity = activity;
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString()
{
return this.label;
}
}
Using this class you are able to bind an Activity to a list item, so when it will be clicked, you will know which Activity to start.
Your Customer.java class will look like:
public class Customer extends ListActivity
{
TextView selection;
CustomerListItem[] items = {
new CustomerListItem("Start Trip", StartTripActivity.class),
new CustomerListItem("Clock in", ClockinActivity.class),
new CustomerListItem("Customer Svc", CustomerSvcActivity.class),
new CustomerListItem("Independent Inspection", IInspectionActivity.class),
new CustomerListItem("Pick Up", PickUpActivity.class),
new CustomerListItem("Log Out", LogoutActivity.class)};
#Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
setListAdapter(new ArrayAdapter<CustomerListItem>(
this, android.R.layout.simple_list_item_1, items));
selection = (TextView) findViewById(R.id.selection);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
final Intent intent = new Intent(this, items[position].getActivity());
startActivityForResult(intent, position);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_OK)
{
// Perform different actions based on from which activity is
// the application returning:
switch (requestCode)
{
case 0:
// TODO: handle the return of the StartTripActivity
break;
case 1:
// TODO: handle the return of the ClockinActivity
break;
case 2:
// TODO: handle the return of the CustomerSvcActivity
// and so on...
break;
default:
break;
}
}
else if (resultCode == RESULT_CANCELED)
{
resultsTxt.setText("Canceled");
}
}
}

onActivityResult Intent data not correct

I'm venturing into startActivityForResult for the first time and I'm running into a problem.
Activity A (ActivityMyList) launches Activity B (ActivityQuickList) waiting for a result:
Intent intentLaunchQuickList = new Intent(ActivityMyList.this, ActivityQuickList.class);
startActivityForResult(intentLaunchQuickList, REQUEST_QUICKLIST);
When a user clicks on a list item of Activity B, it returns "ql_id" to Activity A:
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
QuickListItem qlItem = m_Adapter.getItem(position);
if (qlItem != null && qlItem.getQLId() != -1) {
Intent data = new Intent();
data.putExtra("ql_id", Integer.toString(qlItem.getQLId()));
if (getParent() == null) {
setResult(Activity.RESULT_OK, data);
}
else {
getParent().setResult(Activity.RESULT_OK, data);
}
finish();
}
finish();
}
Integer.toString(qlItem.getQLId()) evaluates to "1". This is important because I am not receiving "1"...
I have overridden the onActivityResult handler in Activity A with this:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_QUICKLIST) {
if (resultCode == Activity.RESULT_OK) {
Bundle extras = data.getExtras();
if (extras != null) {
int id = extras.getInt("ql_id");
}
}
}
}
Unfortunately, extras.getInt("ql_id") evaluates to "0". Why is this? It should be "1". I am clearly doing something incorrectly.
Thank you for your help
Ah, nevermind. I'm putting a String into the bundle and pulling an int out.

Categories

Resources