I have Fragment(F) which calls the activity(A). On press of button(B) in activity(A) the activity must return selected arraylist value back to fragment(F) and finish activity(A)... is this possible?
I know from Activity you can send data with intent as:
Bundle bundle = new Bundle();
bundle.putString("key", "value");
// set Fragmentclass Arguments
Fragmentclass fragmentobj = new Fragmentclass();
fragmentobj.setArguments(bundle);
in Fragment onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("key");
return inflater.inflate(R.layout.fragment, container, false);
}
but this works for calling new fragment not working with same fragment.
My question: is it possible for called Activity to return value to caller fragment?
public class HomeFragment extends Fragment{
Button attachment;
String strtext = "check";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.home_fragment, null);
attachment = (Button) rootView
.findViewById(R.id.btn_activity);
Toast.makeText(getActivity(),
"Key= " + strtext,
Toast.LENGTH_LONG).show();
attachment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(getActivity(), AndroidCustomGalleryActivity.class);
getActivity().startActivityForResult(myIntent,999);
}
});
return rootView;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 999){
strtext = getArguments().getString("key");
Toast.makeText(getActivity(),
"Key= " + strtext,
Toast.LENGTH_LONG).show();
}
}
}
In Called Activity
Bundle bundle = new Bundle();
bundle.putString("key", "value");
HomeFragment fragmentobj = new HomeFragment();
fragmentobj.setArguments(bundle);
finish();
In your fragment(F) call the startActivityForResult() method to start the activity A, then override onActivityResult() method in the fragment.
So when the activity A finishes you can get get the result bundle in onActivityResult() method.
EDIT
In your fragment onClick() call the activity like this
Intent myIintent=new Intent(getActivity(), AndroidCustomGalleryActivity.class);
startActivityForResult(myIintent, 999);
And in your activity
Intent intent = getIntent();
Bundle bundle = new Bundle();
bundle.putString("key", "value");
intent.putExtras(bundle);
setResult(RESULT_OK, intent);
finish();
Now you will get the result in onActivityResult() method of the fragment.
EDIT2
In your fragment onActivityResult() method you have to get the data like this...
Bundle extras = data.getExtras();
strtext = extras.getString("key");
Related
In my code below I created a method which is: I would like to put a variable in putExtra that I can get it in the new activity. The problem is in the new activity gave me the first value(numtelephone) from first element in my list. I know that because of getItem(0), but how can I get the value( numtelephone ) for every element from the list?
public class ListClient extends Activity {
String myJSON,test;
TextView numt;
private static final String TAG_RESULTS="result";
private static final String TAG_NOMCLIENT = "nomclient";
private static String TAG_NUMTELEPHONE ="numtelephone";
private static final String TAG_DEPART ="depart";
private static final String TAG_DESTINATION ="destination";
private static final String TAG_NBRPERSONNE ="nbrpersonne";
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
ListView list;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_client);
list = (ListView) findViewById(R.id.list);
personList = new ArrayList<HashMap<String,String>>();
getData();
}
protected void showList(){
//json parsing etc...
ListAdapter adapter = new SimpleAdapter(
ListClient.this, personList, R.layout.list_item,
new String[]{TAG_NOMCLIENT,TAG_NUMTELEPHONE,TAG_DEPART,TAG_DEPART,TAG_NBRPERSONNE},
new int[]{R.id.name, R.id.numt, R.id.depart, R.id.destination, R.id.nbrpersonne}
);
list.setAdapter(adapter);
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
// json dowload from web, not needed in this question
return "";
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
public void GoUpdate(View v ) {
Intent in = new Intent(getBaseContext(), Update.class);
in.putExtra("NUMTELEPHONE",((HashMap<String, String>)list.getAdapter().getItem(0)).get("numtelephone"));
}
startActivity(in);
}
}
There is simple and only one solution. Delete your xml android:click property of list and add this list#setOnItemClickListener in your onCreate:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_client);
list = (ListView) findViewById(R.id.list);
personList = new ArrayList<HashMap<String,String>>();
getData();
//this thing has been added
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(id!=-1){
Intent in = new Intent(getBaseContext(), Update.class);
in.putExtra("NUMTELEPHONE", ((HashMap<String, String>) list.getAdapter().getItem((int)id)).get("numtelephone")); //TAG_NUMTELEPHONE
startActivity(in);
}
}
});
}
To move it from onCreate do:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_client);
list = (ListView) findViewById(R.id.list);
personList = new ArrayList<HashMap<String, String>>();
getData();
list.setOnItemClickListener(new OnMyListItemClickListener());
}
Context context = this;
private class OnMyListItemClickListener implements AdapterView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(id!=-1){
Intent in = new Intent(context, Update.class);
in.putExtra("NUMTELEPHONE", ((HashMap<String, String>) list.getAdapter().getItem((int) id)).get("numtelephone")); //TAG_NUMTELEPHONE
startActivity(in);
}
}
}
Lesson learned - dont create sucha buttons - they are not aware in which item they are, so you cant extract the id - instead just use something like AlertDialog
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(id!=-1){
AlertDialog.Builder al = new AlertDialog.Builder(context);
al.setMessage("Are you sure you want to do it?");
al.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent in = new Intent(context, Update.class);
in.putExtra("NUMTELEPHONE", ((HashMap<String, String>) list.getAdapter().getItem((int) id)).get(TAG_NUMTELEPHONE));
startActivity(in);
}
});
al.setNegativeButton(android.R.string.no, null);
al.show();
}
}
i created Activity5 for manage values on other activities...
in Activity3 i have a spinner...
Spinner spinner1;
ArrayList<String> SAlist;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity3);
getActionBar().setDisplayHomeAsUpEnabled(true);
Intent intent = getIntent();
ArrayList<String> SAList = intent.getStringArrayListExtra("StringArrayList");
spinner1=(Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adp=new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line,SAList);
spinner1.setAdapter(adp);
}
i think if i build new spinner (for showing it to user) in activity5 and edit it , then passing array list of this spinner to activity3, this is possible...
Activity5:
Spinner sp;
EditText et;
ArrayList<String> li;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity5);
getActionBar().setDisplayHomeAsUpEnabled(true);
li=new ArrayList<String>();
li.add("first item");
sp=(Spinner) findViewById(R.id.spinner1);
Button butt=(Button) findViewById(R.id.button1);
Button butt1=(Button) findViewById(R.id.button2);
et=(EditText)findViewById(R.id.editText1);
add();
butt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
li.add(et.getText().toString());
et.setText(null);
add();
}
});
butt1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity5.this, MainActivity3.class);
intent.putStringArrayListExtra("StringArrayList", li);
startActivity(intent);
}
});
}
private void add() {
ArrayAdapter<String> adp=new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line,li);
sp.setAdapter(adp);
}
but when i launch app and open activity3 it shows "unfortunately app has stopped" !!!
help me plz!
when you open activity3 from main menu, on that event your getting SAList null,
try doing this,when SAList is null it will show empty spinner.
Intent intent = getIntent();
if(intent.getStringArrayListExtra("StringArrayList")!=null)
{
ArrayList<String> SAList = intent.getStringArrayListExtra("StringArrayList");
}else
{
ArrayList<String> SAList=new ArrayList<String>();
}
I have researched this topic thoroughly and found similar questions on StackOverflow but not specific enough for my question. I am trying to update my ListView with a SimpleCursorAdapter. I have a button, "Get Network Location" that when I press it, it dynamically populates my ListView with new location data (id, lat, lon, acc, time) every time the location changes inside method "onLocationChanged". This is done through adding the new location data to the database and setting the cursor to the adapter.
So it works fine until the "Back" button is pressed or the phone changes orientation. In onResume, the listview becomes empty, so I had to open the database again and set the cursor to the adapter and the adapter to listview again. This populates the listview with complete data from database at the time that "onResume" is called.
However, when a new location data gets added in "onLocationChanged", the new data doesn't populate the listview, until "onResume" gets called again. adapter.notifyDataSetChanged is called both in "onResume" an "onLocation" changed but to no avail. My guess is the listview has changed to a different one after "onCreate" is called but I don't know how to resolve that.
Please anyone with knowledge on this issue let me know what is wrong with my code.
Here's my code:
public class MainActivity extends Activity {
LocationManager locMan;
String provider;
Boolean netWork_enabled = false;
private static long MINTIME;
private static float MINDIS;
Cursor cursor;
NetworkScanDB GeoLocInfoDb;
String row;
double lat;
double lon;
double accur;
double time;
EditText etMinTime;
EditText etMinDis;
ListView lv;
SimpleCursorAdapter sd;
String[] columns;
int[] to;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initialize lv
lv = (ListView) findViewById(R.id.listView1);
// getting min time and distance from edit text
etMinTime = (EditText) findViewById(R.id.et_minTime);
etMinDis = (EditText) findViewById(R.id.et_minDis);
// initiating location
locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = locMan.NETWORK_PROVIDER;
try {
netWork_enabled = locMan.isProviderEnabled(provider);
} catch (Exception ex) {
}
columns = new String[] { NetworkScanDB.Key_RowID,
NetworkScanDB.Key_Lat, NetworkScanDB.Key_Lon,
NetworkScanDB.Key_Accur, NetworkScanDB.Key_Time };
to = new int[] { R.id.t0, R.id.t1, R.id.t2, R.id.t3, R.id.t4 };
sd = new SimpleCursorAdapter(MainActivity.this, R.layout.nsrow, cursor,
columns, to, 0); // had to change to api 11., 0=no query
}
LocationListener locationListenerNetwork = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
try {
GeoLocInfoDb = new NetworkScanDB(MainActivity.this);
GeoLocInfoDb.open();
// insert row into DB
GeoLocInfoDb.insertGeoLocInfo(location.getLatitude(),
location.getLongitude(), location.getAccuracy(),
location.getTime());
cursor = GeoLocInfoDb.getGeoLocInfoCursor();
sd = new SimpleCursorAdapter(MainActivity.this, R.layout.nsrow,
cursor, columns, to, 0); // had to change to api 11.,
// 0=no query
Toast.makeText(getApplicationContext(),
"added new location onLocationChanged",
Toast.LENGTH_LONG).show();
// lv = (ListView) findViewById(R.id.listView1);
sd.notifyDataSetChanged();
lv.setAdapter(sd);
GeoLocInfoDb.close();
} catch (Exception e) {
Log.w("nwscan", e.toString());
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
};
public void getNetworkLocation(View v) {
MINTIME = Long.parseLong(etMinTime.getText().toString());
MINDIS = Float.parseFloat(etMinDis.getText().toString());
if (netWork_enabled) {
locMan.requestLocationUpdates(provider, MINTIME, MINDIS,
locationListenerNetwork);
} else {
Toast.makeText(getApplicationContext(), "network not enable",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
Toast.makeText(getApplicationContext(), "onResume ", Toast.LENGTH_LONG)
.show();
GeoLocInfoDb = new NetworkScanDB(MainActivity.this);
GeoLocInfoDb.open();
cursor = GeoLocInfoDb.getGeoLocInfoCursor();
sd = new SimpleCursorAdapter(MainActivity.this, R.layout.nsrow, cursor,
columns, to, 0); // had to change to api 11., 0=no query
sd.notifyDataSetChanged();
lv.setAdapter(sd);
}
...
}
I am making a request to the Facebook API using the Facebook SDK. I am trying to retrieve a graph user however it doesnt matter what I do. The callback is not being triggered.
How do I trigger the OnActivityResult of the fragment?
public class SampleFragment
extends Fragment
{
FacebookUtils instance;
private TextView labelText;
private ProfilePictureView prof;
private Button button;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View contentView = inflater.inflate(R.layout.fragment_sample, container, false);
labelText = ((TextView) contentView.findViewById(R.id.label_text));
prof = (ProfilePictureView)contentView.findViewById(R.id.selection_profile_pic);
button= ((Button) contentView.findViewById(R.id.button));
Bundle bundle = getArguments();
String label = bundle.getString("label");
labelText.setText(label);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
// If the session is open, make an API call to get user data
// and define a new callback to handle the response
Request request = Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
// If the response is successful
Toast.makeText(getActivity(),user.getFirstName(),Toast.LENGTH_LONG).show();
if (session == Session.getActiveSession()) {
if (user != null) {
prof.setProfileId(user.getId());
AppMsg.makeText(getActivity(),user.getFirstName(),AppMsg.STYLE_CONFIRM).show();
//user id
//profileName = user.getName();//user's profile name
//userNameView.setText(user.getName());
}
}
}
});
Request.executeBatchAsync(request);
}
}
});
return contentView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(getActivity(), requestCode, resultCode, data);
}
Here is the activity ShowData.java where i am setting up customized listview.. Now i need to click view on that listview and need to display another activity but throws force close.. It throws error on listview.setAdapter(adapter);
public class ShowData extends Activity
{
ListView listview;
Intent intent;
ArrayList<BeanClass> datalist;
CustomAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
listview = (ListView) findViewById(R.id.listView1);
Intent intent = getIntent();
datalist = (ArrayList<BeanClass>) intent.getSerializableExtra("list");
Log.i("Size of ArrayList", "is " +datalist.size());
adapter = new CustomAdapter(ShowData.this, R.layout.customrow , datalist);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3)
{
Intent i = new Intent(ShowData.this,DetailActivity.class);
i.putExtra("datalist", datalist);
i.putExtra("position", arg2);
startActivity(i);
}
}
}
Here is the CustomAdapter.java
public class CustomAdapter extends ArrayAdapter<BeanClass>
{
Context context;
int layoutResourceId;
BeanClass bc;
ArrayList<BeanClass> vbc;
public CustomAdapter(Context context, int layoutResourceId, ArrayList<BeanClass> vbc)
{
super(context, layoutResourceId, vbc);
this.context=context;
this.layoutResourceId=layoutResourceId;
this.vbc=vbc;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
StringReaderHolder holder;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent,false);
holder= new StringReaderHolder();
holder.mytext1 = (TextView) row.findViewById(R.id.textView1);
holder.mytext2 = (TextView) row.findViewById(R.id.textView2);
holder.mytext3 = (TextView) row.findViewById(R.id.textView3);
row.setTag(holder);
}
else
{
holder = (StringReaderHolder) row.getTag();
}
BeanClass bsObject = vbc.get(position);
holder.mytext1.setText(bsObject.name);
holder.mytext2.setText(bsObject.address);
holder.mytext3.setText(bsObject.phone);
return row;
}
static class StringReaderHolder
{
TextView mytext1,mytext2,mytext3;
}
}
How should i use setOnItemClickListener...??? Thanks...
In Your getView Method try:
row.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(context,DetailActivity.class);
i.putExtra("datalist", vbc);
i.putExtra("position", position);
startActivity(i);
}
});