Android passing data from fragment to fragment - android

I want to pass data from A fragment to B fragment.. And then B fragment to A fragment. But when i pass A to B, it was perfect. But when i pass B to A, it gives me nullpointexception.
My Code is here,
A Fragment,
public static PlayRadioFragment newInstance(String url, String name, String value) {
Bundle args = new Bundle();
args.putString(URL, url);
args.putString(NAME, name);
args.putString(VALUE, value);
PlayRadioFragment fragment = new PlayRadioFragment();
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.play_radio, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
try {
url = getArguments().getString(URL);
if (url.length() > 0) {
url_string = getArguments().getString(URL);
name_string = getArguments().getString(NAME);
image_url = getArguments().getString(VALUE);
value = getArguments().getString(VALUE);
name.setText(name_string);
Log.e("url", url_string);
Log.e("name", name_string);
playRadio();
image = (ImageView) getView().findViewById(R.id.imageView);
if (image_url.length() != 0) {
Picasso.with(getActivity()).load(image_url).fit()
.tag(this).into(image);
}
} else {
try {
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
digest.update(package_name.trim().getBytes());
byte messageDigest[] = digest.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++)
hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
getRadioChannelList(hexString.toString());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (NullPointerException e) {
try {
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
digest.update(package_name.trim().getBytes());
byte messageDigest[] = digest.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++)
hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
getRadioChannelList(hexString.toString());
} catch (NoSuchAlgorithmException e2) {
e.printStackTrace();
} catch (JSONException e2) {
e.printStackTrace();
}
e.printStackTrace();
}
actionPlayStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (url_string.length() > 0) {
Intent intent = new Intent(getActivity(),
RadioService.class);
if (mRadioService != null) {
getActivity().stopService(intent);
unBindMyService();
} else {
playRadio();
}
}
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent i=new Intent(getActivity(),
PreferenceActivity.class);
startActivity(i);
break;
case R.id.radio_list:
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(channelList,
new TypeToken<List<ChannelPojo>>() {
}.getType());
((MainActivity2) getActivity()).changeFragment(new MainFragment().newInstance(element.getAsJsonArray()
.toString(), value));
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
B fragment,
public static MainFragment newInstance(String url, String value) {
Bundle args = new Bundle();
args.putString(URL, url);
args.putString(VALUE, value);
MainFragment fragment = new MainFragment();
fragment.setArguments(args);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.list_main_activity, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
AdView adView = (AdView) getView().findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
value = getArguments().getString(VALUE);
Gson gson = new Gson();
Type type = new TypeToken<List<ChannelPojo>>() {
}.getType();
channelList = gson.fromJson(getArguments().getString(URL), type);
list = (ListView) getView().findViewById(R.id.listView);
adapter = new RadioChannelAdapter(getActivity(), channelList);
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
MCrypt mcrypt = new MCrypt();
String url = "";
try {
url = new String(mcrypt.decrypt(channelList.get(i).getUrl()));
url = URLDecoder.decode(url, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
((MainActivity2) getActivity()).changeFragment(new PlayRadioFragment().newInstance(url, channelList.get(i).getName(), value));
}
});
}
MainActivity,
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
changeFragment(new PlayRadioFragment());
}
public void changeFragment(Fragment f) {
String backStateName = f.getClass().getName();
FragmentManager manager = getSupportFragmentManager();
boolean fragmentPopped = manager
.popBackStackImmediate(backStateName, 0);
if (!fragmentPopped) {
FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.container, f, "Radio");
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(backStateName);
ft.commit();
}
}
But i cant getting what is problem to pass from B to A fragment. Please help me.. Thank you.

I think there is a problem with this line :
changeFragment(new PlayRadioFragment()); // do not initialize fragment like this
Following your Fragment structure I think Whenever you want to create an instance of fragment then please use this code to initiate it.
MainFragment mainFragment = MainFragment.newInstance("url", "value");
Thanks.

Try this;
Create interface in each fragment
Inside each interface, consume the Data
Implement both interfaces in your Activity Class.
Inside each overridden methods, pass the values to each fragment.

Related

transfer data from activity to fragment using bundle or intent

i want to transfer data from activity to fragment, it always prints this error. i tried to use different techniques to overcome this like intent but still stuck. do i miss something in my code in activity or in the fragment ?
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.junaida.project1, PID: 14447
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.junaida.project1/com.example.junaida.project1.Year}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2957)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3018)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6724)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at com.example.junaida.project1.fragments.CardFragment.onCreateView(CardFragment.java:89)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2354)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1419)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1740)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1809)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:799)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2580)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2367)
at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2229)
at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3221)
at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3171)
at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:192)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:560)
at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:177)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1256)
at android.app.Activity.performStart(Activity.java:6959)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3018) 
at android.app.ActivityThread.-wrap14(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1653) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6724) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410) 
this error points to
String id = bundle.getString("id");
i will list the class where i transfer data from
public class Year extends AppCompatActivity {
ImageView back;
GridView grid;
String id;
String type;
String year;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_year);
Intent data = getIntent();
year = data.getStringExtra("year");
id = data.getStringExtra("id");
type = data.getStringExtra("type");
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
//show the original color of icons
bottomNavigationView.setItemIconTintList(null);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
final Bundle bundle = new Bundle() ;
Intent intent;
switch (item.getItemId()) {
case R.id.action_item1:
bundle.putString("year",year);
bundle.putString("id",id);
bundle.putString("type",type);
//selectedFragment.setArguments(bundle);
selectedFragment = new CardFragment();
selectedFragment.setArguments(bundle);
break;
case R.id.action_item2:
bundle.putString("year",year);
bundle.putString("id",id);
bundle.putString("type",type);
//selectedFragment.setArguments(bundle);
selectedFragment = new AudioFragment();
selectedFragment.setArguments(bundle);
break;
case R.id.action_item3:
bundle.putString("year",year);
bundle.putString("id",id);
bundle.putString("type",type);
//selectedFragment.setArguments(bundle);
selectedFragment = new VideoFragment();
selectedFragment.setArguments(bundle);
break;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content_frame2, selectedFragment);
transaction.commit();
return true;
}
});
//Manually displaying the first fragment - one time only
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content_frame2, new CardFragment());
transaction.commit();
back = (ImageView)findViewById(R.id.back_year);
back.setOnClickListener(new AdapterView.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
});
}
}
my fragment is
public class CardFragment extends Fragment {
// String id;
// String type;
// String year;
private ListAdapter adapter;
TextView textView;
private ListView lv;
private List<ListItemsData> list = new ArrayList<ListItemsData>();
private static final String url = "http://10.94.0.204/WebApplication7/api/subjects";
public CardFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = this.getArguments();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_card, container, false);
//final ArrayList<ListItemsData> listItem = GetlistItems();
Bundle bundle = this.getArguments();
String id = bundle.getString("id");
String year = bundle.getString("year");
String type = bundle.getString("type");
final Activity mActivity = this.getActivity();
// lv.setAdapter(new ListAdapter(getActivity(), listItem));
adapter = new ListAdapter(getContext(), list);
lv.setAdapter(adapter);
try {
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
String URL = "http://10.94.0.204/WebApplication7/api/subjects";
JSONObject jsonBody = new JSONObject();
// jsonBody.put("tblRegisteredUsers_nickName", username.getText().toString().trim());
jsonBody.put("id", id.toString());
jsonBody.put("Type", type.toString());
jsonBody.put("Year", year.toString());
final String requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.equals("success")) {
//login authenticated. Start the next activity of your app
Toast.makeText(getActivity(), response.toString(), Toast.LENGTH_LONG).show();
// Toast.makeText(getApplicationContext(), "registered successfully ", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(), MainActivity.class);
// intent.putExtra("id", Id);
// intent.putExtra("year", year);
startActivity(intent);
} else {
//login failed. prompt to re-enter the credentials
Toast.makeText(mActivity.getApplicationContext(), "Failed to log In", Toast.LENGTH_SHORT).show();
Log.i("VOLLEY", response);
Toast.makeText(mActivity.getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
})
{
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
return null;
}
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString;
String json = null;
try {
json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
responseString = String.valueOf(json).trim();
ArrayList<Response4> list_response = new ArrayList<Response4>();
Type listType = new TypeToken<List<Response4>>() {
}.getType();
list_response = new Gson().fromJson(responseString, listType);
//String check = list.get(0).getMessagesName();
for (int i = 0; i < list_response.size(); i++) {
// JSONObject obj = response.getJSONObject(i);
ListItemsData listItemData = new ListItemsData();
listItemData.setItem(list_response.get(i).getMessagesName());
listItemData.setUrl(list_response.get(i).getMessageURLNew());
//listItemData.setUrl((obj.getString("url")));
list.add(listItemData);
//Id = list.get(0).getId();
// year = list.get(0).getYear();
//Response2 yourModel = new Gson().fromJson(responseString, Response2.class);
}
// i should have this peice of code for methods that are in the background
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged();
}
});
// String Check = yourModel.getMessagetitle();
return Response.success(list_response.toString(), HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return rootView;
}
am i sending the data in correct way ?
any help would be appreciated
You should be using getArguments() when getting the bundle from the fragment.
get the bundle like this
public View onCreateView(LayoutInflater inflater, ViewGroup containerObject,Bundle savedInstanceState){
//here is your arguments
Bundle bundle=getArguments();
//get string like this
String year = bundle.getString("year");
}
edit : make a function like this and add to your default fragment as well as other fragment starting from navigation menu.
private Bundle getBundle(Intent data){
Bundle bundle = new Bundle();
bundle.putString("year",data.getStringExtra("year"));
bundle.putString("id",data.getStringExtra("id"));
bundle.putString("type",data.getStringExtra("type"));
}
here is final code
public class Year extends AppCompatActivity {
ImageView back;
GridView grid;
String id;
String type;
String year;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_year);
Intent data = getIntent();
//get a bundle set and ready to use anytime
Bundle myBundle= getBundle(data);
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
//show the original color of icons
bottomNavigationView.setItemIconTintList(null);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.action_item1:
selectedFragment = new CardFragment();
selectedFragment.setArguments(myBundle);
break;
case R.id.action_item2:
selectedFragment = new AudioFragment();
selectedFragment.setArguments(myBundle);
break;
case R.id.action_item3:
selectedFragment = new VideoFragment();
selectedFragment.setArguments(myBundle);
break;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content_frame2, selectedFragment);
transaction.commit();
return true;
}
});
//Manually displaying the first fragment - one time only
CardFragment myCardFragment = new CardFragment();
myCardFragment.setArguments(myBundle);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content_frame2, myCardFragment);
transaction.commit();
back = (ImageView)findViewById(R.id.back_year);
back.setOnClickListener(new AdapterView.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
});
}
private Bundle getBundle(Intent data){
Bundle bundle = new Bundle();
bundle.putString("year",data.getStringExtra("year"));
bundle.putString("id",data.getStringExtra("id"));
bundle.putString("type",data.getStringExtra("type"));
}
}

null object in onSaveInstanceState method

i'm trying to save object(saveMOvie) in onSaveinstanceState to restore it on screen rotated when debugging the code using tablet with main and detail fragments are next to each other the value of object (saveMOvie) is null but when using mobile phone with only one fragment on screen the value of object (saveMOvie) doesn't equal null could anyone tell me why ??
MainActivityFragment
public class MainActivityFragment extends Fragment {
Movie moviesStore[];
GridView gridView;
String[] moviesImages;
View rootView;
ImageAdapter imgadpt;
boolean flag;
OnNewsItemSelectedListener onis;
Movie saveMOvie = new Movie();
public interface OnNewsItemSelectedListener {
public void onMovieSelected(Movie movie);
}
public MainActivityFragment() {
}
public static boolean isTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK)
>= Configuration.SCREENLAYOUT_SIZE_LARGE;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();//3shan myy7slash duplicate
inflater.inflate(R.menu.menu_main, menu);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
onis = (OnNewsItemSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnNewsItemSelectedListener");
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.open_settings_activity) {
Intent intent = new Intent(getActivity(), SettingsActivity.class);
startActivity(intent);
//refresh used when there is no connection
} else if (id == R.id.Refresh_activity) {
onStart();
}
return super.onOptionsItemSelected(item);
}
public void updateMovies() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String mode = prefs.getString(getString(R.string.key),
getString(R.string.default_value));
if (mode.equals("popular") || mode.equals("top_rated")) {
new FetchMovies().execute(mode);
} else {
if (flag) {
android.support.v4.app.FragmentManager fm = getActivity().getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fm.beginTransaction();
FavouriteActivityFragment fav = new FavouriteActivityFragment();
fragmentTransaction.replace(R.id.frag_main, fav);
// fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
} else {
Intent intent = new Intent(getActivity(), FavouriteActivity.class);
startActivity(intent);
}
}
}
#Override
public void onStart() {
super.onStart();
transaction.commit();
flag = isTablet(getActivity());
ConnectivityManager cn = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nf = cn.getActiveNetworkInfo();
if (nf == null && nf.isConnected() != true) {
Snackbar snackbar = Snackbar
.make(rootView, "Network Not Available", Snackbar.LENGTH_LONG)
.setAction("RECONNECT", new View.OnClickListener() {
#Override
public void onClick(View view) {
onStart();
}
});
snackbar.show();
}
updateMovies();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("movie",saveMOvie);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (savedInstanceState != null) {
onis.onMovieSelected(saveMOvie);
}
setHasOptionsMenu(true);
rootView = inflater.inflate(R.layout.fragment_main, container, false);
gridView = (GridView) rootView.findViewById(R.id.gridView);
return rootView;
}
public class FetchMovies extends AsyncTask<String, Void, Movie[]> {
private final String Log_Tag = FetchMovies.class.getSimpleName();
private Movie[] getMovieDataFromJson(String moviesJasonStr)
throws JSONException
{
final String lists = "results";
final String decription = "overview";
final String originalTitle = "original_title";
final String moviePoster = "poster_path";
final String userRating = "vote_average";
final String releaseDate = "release_date";
final String id = "id";
JSONObject moviesJason = new JSONObject(moviesJasonStr);
JSONArray moviesArray = moviesJason.getJSONArray(lists);
// String[] resultStrs = new String[moviesArray.length()];
moviesStore = new Movie[moviesArray.length()];
for (int i = 0; i < moviesArray.length(); i++) {
JSONObject oneMovieInfo = moviesArray.getJSONObject(i);
moviesStore[i] = new Movie();
moviesStore[i].setPlotSynopsis(oneMovieInfo.getString("overview"));
moviesStore[i].setUserRating(oneMovieInfo.getString("vote_average"));
moviesStore[i].setReleaseDate(oneMovieInfo.getString("release_date"));
moviesStore[i].setOriginalTitle(oneMovieInfo.getString("original_title"));
moviesStore[i].setMoviePoster(oneMovieInfo.getString("poster_path"));
moviesStore[i].setId(oneMovieInfo.getString("id"));
}
return moviesStore;
}
#Override
protected Movie[] doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String moviesJasonStr = null;
StringBuilder baseUrl = new StringBuilder("https://api.themoviedb.org/3/movie/");
baseUrl.append(params[0]);
baseUrl.append("?api_key=");
baseUrl.append(BuildConfig.MOVIE_DP_API_KEY);
try {
// URL url = new URL("https://api.themoviedb.org/3/movie/popular?api_key=d51b32efc0520227b7c1c67e0f6417f6");
URL url = new URL(baseUrl.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
moviesJasonStr = buffer.toString();
Log.v(Log_Tag, "movies Jason String :" + moviesJasonStr);
} catch (IOException e) {
Log.e(Log_Tag, "Error ", e);
// Toast.makeText(getActivity(),"there is no internet connection",Toast.LENGTH_LONG).show();
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(Log_Tag, "Error closing stream", e);
}
}
}
try {
return getMovieDataFromJson(moviesJasonStr);
} catch (JSONException e) {
Log.e(Log_Tag, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Movie[] result) {
if (result != null) {
moviesImages = new String[result.length];
for (int i = 0; i < result.length; i++) {
StringBuilder baseUrl = new StringBuilder();
baseUrl.append("http://image.tmdb.org/t/p/w185/");
baseUrl.append(result[i].getMoviePoster());
moviesImages[i] = baseUrl.toString();
}
imgadpt = new ImageAdapter(getActivity(), moviesImages);
gridView.setAdapter(imgadpt);
// if(flag){
// onis.onMovieSelected(moviesStore[0]);}
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
String posterUrl = (String) imgadpt.getItem(position);
saveMOvie = moviesStore[position];
if (flag) {
onis.onMovieSelected(moviesStore[position]);
} else {
Intent intent = new Intent(getActivity(), DetailActivity.class);
intent.putExtra("movie", moviesStore[position]);
startActivity(intent);
}
}
});
} else {
Toast.makeText(getActivity(), "Cannot Fetch Data from api check your internet Connection", Toast.LENGTH_LONG).show();
}
}
}
}
When onCreate(savedInstanceState) is called, check whether savedInstanceState is null, and if not, then getExtras from it (as it's a Bundle).
if (savedInstanceState != null)
savedInstanceState.getParcelable(key)
Then do whatever you'd like with the object.

Fragment is running the webservice after each button click

I have an app that reads and display data from a weather API as show below.
Now those data you see in the RecyclerView are displayed via a Fragment. What happens is when I click the Forecast button in the toolbar the web service service is running again. Which means that the Fragment is added in the stack/click.
So here is my logic how to fix that. If the stack is null then add the Fragment. If not then don't.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.forecast) {
String tag = "forecastFragment";
Fragment f = getSupportFragmentManager().findFragmentByTag(tag);
if (f == null) {
ForecastFragment forecastFragment = new ForecastFragment();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.main_content, forecastFragment, "forecastfragment");
ft.addToBackStack("added today current");
forecastFragment.setArguments(b);
fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
ft.commit();
} else{
getSupportFragmentManager().findFragmentById(R.id.main_content);
}
}
return super.onOptionsItemSelected(item);
}
Here is what I did, but still the web service is running every time I click the Forecast button.
Any ideas?
Here is my Webservice that is run by the ForecastFragment.
class ForecastFragment extends Fragment {
private static final String FORECAST_KEY = "forecast";
public static String URL=
"http://api.openweathermap.org/data/2.5/forecast/daily?";
EditText editText;
public static String BASE_URL= "";
private String IMG_URL ="http://api.openweathermap.org/img/w/";
private String retrievedLat;
private String retrievedLog;
private RecyclerView mRecyclerView;
ImageView imageView;
public ArrayList<Model> modelList;
private Model m;
WeekForecastAdapter adapter;
public ForecastFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_forecast, container, false);
retrievedLat = getArguments().getString("lat");
retrievedLog = getArguments().getString("log");
//http://api.openweathermap.org/data/2.5/forecast/daily?lat=35&lon=139&units=metric&cnt=10&mode=json&appid=d48708e1e4d8e2b60da14778acd8d56a
BASE_URL = URL +"lat="+retrievedLat+"&lon="+retrievedLog+"&units=metric&cnt=10&mode=json&appid=d48708e1e4d8e2b60da14778acd8d56a";
modelList = new ArrayList<>();
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView = (RecyclerView)rootView.findViewById(R.id.week_forecast_recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(linearLayoutManager);
adapter = new WeekForecastAdapter(getActivity(),modelList);
mRecyclerView.setAdapter(adapter);
if(savedInstanceState!=null){
ArrayList<Model> items = savedInstanceState.getParcelableArrayList(FORECAST_KEY);
modelList = savedInstanceState.getParcelableArrayList(FORECAST_KEY);
adapter.setModel(items);
}else {
if(isOnline()) {
weekWeatherData();
}else{
Toast.makeText(getActivity(),"No internet connection",Toast.LENGTH_SHORT).show();
}
}
return rootView;
}
private void weekWeatherData() {
modelList.clear();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
BASE_URL,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("TAG", response.toString());
try {
m = new Model();
JSONObject cityObject = response.getJSONObject("city");
String city = cityObject.getString("name");
String country = cityObject.getString("country");
JSONArray jsonObject = response.getJSONArray("list");
for(int i = 0;i<jsonObject.length();i++){
m = new Model();
m.setCity(city);
m.setCountry(country);
//list:
// {"dt":1464343200,"temp":{"day":23.05,"min":8.65,"max":24.96,"night":13.22,"eve":24.85,"morn":8.65},
// "pressure":950.2,"humidity":41,"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"
// }],
// "speed":1.16,"deg":342,"clouds":0}
JSONObject innerJSON = jsonObject.getJSONObject(i);
long dateTime = innerJSON.getLong("dt");
Date weekDay = new Date(dateTime * 1000L);
SimpleDateFormat outFormat = new SimpleDateFormat("EEEE");
String day = outFormat.format(weekDay);
SimpleDateFormat outFormat1 = new SimpleDateFormat("dd MMM");
String date = outFormat1.format(weekDay);
m.setDay(day);
m.setDate(date);
m.setDay(day);
//temp:{"day":26.92,"min":19.48,"max":26.92,"night":19.48,"eve":25.65,"morn":26.92}
JSONObject tempObject = innerJSON.getJSONObject("temp");
m.setTemperature(tempObject.getString("day"));
m.setMaxTemperature(tempObject.getString("max"));
m.setMinTemperature(tempObject.getString("min"));
double pressure = innerJSON.getDouble("pressure");
int humidity = innerJSON.getInt("humidity");
m.setPressure(String.valueOf(pressure));
m.setHumidity(String.valueOf(humidity));
JSONArray weather = innerJSON.getJSONArray("weather");
for(int j=0;j<weather.length();j++){
JSONObject weatherObject = weather.getJSONObject(j);
m.setDescription(weatherObject.getString("description"));
m.setImageIcon(IMG_URL+weatherObject.getString("icon"));
}
double speed = innerJSON.getDouble("speed");
m.setSpeed(String.valueOf(speed));
modelList.add(m);
}
} catch (JSONException e) {
Log.e("TAG", e.toString());
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.v("Theo","onSaveInstanceState called");
outState.putParcelableArrayList(FORECAST_KEY,modelList);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.v("Theo","onDestroy called");
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
}
Change:
ft.replace(R.id.main_content, forecastFragment, "forecastfragment");
To:
ft.replace(R.id.main_content, forecastFragment, tag);
Because your tag (i.e. "forecastFragment") string value is different than the tag you are passing while adding the fragment (i.e. "forecastfragment"). That's why it is not able to find the fragment by tag and adding it everytime on clicking.
I found another solution too.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.forecast) {
ForecastFragment forecastFragment = null;
int backStackEntryCount =
getSupportFragmentManager().getBackStackEntryCount();
if (backStackEntryCount == 0 && forecastFragment == null) {
forecastFragment = new ForecastFragment();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.main_content, forecastFragment);
ft.addToBackStack("added today current");
forecastFragment.setArguments(b);
//fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
ft.commit();
}else{
//getSupportFragmentManager().findFragmentById(R.id.main_content);
}
}
return super.onOptionsItemSelected(item);
}

NullpointException at getActivity() after fragment transaction

I'm fighting with this for a week, without luck.
From the begining:
There is an Activity with Navigation Drawer included. This activity has it's own fragments. Fragments have logic to send requests to a weather api and logic to update themselves with given data. At the first run everything seems to work fine! I'm able to send request and fill views with given data (using okHttp).
Everything is starting to collapse after fragments recreations, I'm getting constantly getActivity() to be null ;(
Code Sample below:
Fragments first initialisation:
public abstract class DoubleFragmentActivity extends AppCompatActivity {
protected static final String TOP_FRAGMENT = "TOP_FRAGMENT";
protected static final String BOTTOM_FRAGMENT = "BOTTOM_FRAGMENT";
protected abstract Fragment topFragment();
protected abstract Fragment bottomFragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_container);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.topFragmentContainer, topFragment(), TOP_FRAGMENT)
.add(R.id.bottomFragmentContainer, bottomFragment(), BOTTOM_FRAGMENT)
.commit();
getSupportFragmentManager().executePendingTransactions();
}
}
}
Navigation Drawer:
private void selectDrawerItem(MenuItem menuItem) {
Fragment f;
Fragment f2;
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
switch (menuItem.getItemId()) {
case R.id.forecastFragment:
f = getSupportFragmentManager().findFragmentByTag("TOP_FRAGMENT");
f2 = getSupportFragmentManager().findFragmentByTag("BOTTOM_FRAGMENT");
if (f != mCurrentForecastFragment || f2 != mDailyForecastFragment) {
ft.replace(R.id.topFragmentContainer, new CurrentForecastFragment(), "TOP_FRAGMENT");
ft.replace(R.id.bottomFragmentContainer, new DailyForecastFragment(), "BOTTOM_FRAGMENT");
} else {
}
break;
case R.id.settingsFragment:
mToolbar.setVisibility(View.INVISIBLE);
f = new SettingsFragment();
ft.replace(R.id.topFragmentContainer, f);
break;
case R.id.paymentsFragment:
f = new PaymentsFragment();
ft.replace(R.id.topFragmentContainer, f);
break;
case R.id.aboutFragment:
break;
default:
}
getSupportFragmentManager().executePendingTransactions();
ft.commit();
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
mDrawer.closeDrawers();
}
Fragment`s logic for connecting and fullfilling data:
public void makeConnectionToApi(String lat, String lon) {
mWeatherParams.setLanguage(Locale.getDefault().getLanguage());
Activity a = getActivity();
Uri.Builder currentBuilder = new Uri.Builder();
currentBuilder.scheme("http")
.authority("api.openweathermap.org")
.appendPath("data")
.appendPath("2.5")
.appendPath("weather")
.appendQueryParameter(WeatherConstants.KEY_LATITUDE, lat)
.appendQueryParameter(WeatherConstants.KEY_LONGITUDE, lon)
.appendQueryParameter(WeatherConstants.KEY_UNITS, mUnit)
.appendQueryParameter(WeatherConstants.KEY_LANGUAGE, mWeatherParams.getLanguage())
.appendQueryParameter("APPID", "###");
String currentUrl = currentBuilder.build().toString();
if (mUtility.isNetworkAvalaible()) {
Request requestCurrent = new Request.Builder().url(currentUrl).build();
//FIRST CALL
mCall = client.newCall(requestCurrent);
mCall.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
Bundle args = new Bundle();
args.putString(TAG, e.toString());
Utility.invokeDialog(TAG, e.toString(), getFragmentManager());
}
#Override
public void onResponse(Response response) throws IOException {
String responseBody = String.valueOf(response.body().string());
try {
mForecast.setCurrent(fetchCurrent(responseBody));
} catch (JSONException e) {
e.printStackTrace();
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
fillViewWithValues();
}
});
}
});
} else {
Utility.invokeDialog(TAG, "Check your internet connection!", getFragmentManager());
}
}
private Current fetchCurrent(String responseBody) throws JSONException {
Current current = new Current();
JSONObject jo = new JSONObject(responseBody);
//FETCH WEATHER ARRAY
JSONArray weather = jo.getJSONArray(WeatherConstants.KEY_CURRENT_CONDITIONS_ARRAY);
for (int j = 0; j < weather.length(); j++) {
JSONObject weatherParser = weather.getJSONObject(j);
current.setIcon(weatherParser.getString(WeatherConstants.KEY_ICON_ID));
Log.i(TAG, "Icons ID: " + weatherParser.getString(WeatherConstants.KEY_ICON_ID));
current.setConditions(weatherParser.getString(WeatherConstants.KEY_DESCRIPTION));
}
//FETCH TEMP
JSONObject temp = jo.getJSONObject(WeatherConstants.KEY_MAIN_OBJECT);
current.setDay(temp.getDouble(WeatherConstants.KEY_TEMP));
current.setPressure(temp.getDouble(WeatherConstants.KEY_PRESSURE));
current.setHumidity(temp.getDouble(WeatherConstants.KEY_HUMIDITY));
current.setDayMax(temp.getDouble(WeatherConstants.KEY_TEMP_DAY_MAX));
// FETCH VISIBILITY
if (jo.has(WeatherConstants.KEY_VISIBILITY)) {
current.setVisibility(jo.getInt(WeatherConstants.KEY_VISIBILITY));
}
//FETCH WIND
JSONObject wind = jo.getJSONObject(WeatherConstants.KEY_WIND_OBJECT);
current.setWindSpeed(wind.getDouble(WeatherConstants.KEY_WIND_SPEED));
if (wind.has(WeatherConstants.KEY_WIND_DEGREES)) {
current.setWindDegrees(wind.getInt(WeatherConstants.KEY_WIND_DEGREES));
}
JSONObject clouds = jo.getJSONObject(WeatherConstants.KEY_CLOUDS);
current.setClouds(clouds.getInt("all"));
current.setTimeStamp(jo.getInt(WeatherConstants.KEY_TIMESTAMP));
current.setCurrentLocation(jo.getString(WeatherConstants.KEY_CITY_NAME));
return current;
}
private void fillViewWithValues() {
Current current = mForecast.getCurrent();
if (mDeegreSwitch == 0) {
mCurrentTemperature.setText(current.getDay() + "\u00B0");
// setBackgroundColor(current.getDay());
} else {
int c = current.getDay();
double f = (9.0 / 5.0) * c + 32;
int e = (int) Math.round(f);
mCurrentTemperature.setText(String.valueOf((int) Math.round(f)) + "\u00B0");
// setBackgroundColor(e);
}
mCurrentCondition.setText(current.getConditions());
mPressure.setText(String.valueOf(current.getPressure()) + "hPa");
mClouds.setText(String.valueOf(current.getClouds()) + "%");
mHumidity.setText(String.valueOf(current.getHumidity()) + "%");
mCurrentIcon.setImageResource(current.getIcon());
}
Problems occurs here: getActivity().runOnUiThread inside makeConnectionToApi method. I've tried to fetch an activity from onAttach method and pass it makeConnectionToApi as parameter, it worked...but partially. App didn't crash but fragment`s view was not updated, like there was a second fragment underneath or something.
I have filling it might be something with threads or I'm doing sth wrong with fragments transaction...

onBackPressed makes the app to crash

I got one activity with several fragments, i use the intent to open the activity, all runs correctly, but when i press the android back button to return to the previous activity makes the app to crash, when i click in the home button the app runs normally... i will post the code to see whats is happening...thanks in advice
The Activity who crashs when the android button is pressed
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_os);
Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Bundle id = getIntent().getExtras();
String get = id.getString("id");
String coiso = id.getString("versao");
String tab = id.getString("tab");
int position = Integer.parseInt(tab);
int intOS = Integer.parseInt(get);
int Versao = Integer.parseInt(coiso);
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true);
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.selector);
}
});
tabs.setViewPager(pager);
pager.setCurrentItem(position);
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(OS.this, MainActivity.class);
intent.putExtra("position", 2);
startActivity(intent);
}
The fragment who open this activity
public static VersaoOrdemServico newInstance(String param1) {
VersaoOrdemServico fragment = new VersaoOrdemServico();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
fragment.setArguments(args);
return fragment;
}
public VersaoOrdemServico() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View tela = inflater.inflate(R.layout.fragment_versao_ordem_servico, container, false);
final ListView lView = (ListView)tela.findViewById(R.id.ListaVersaoOS);
adpt = new OSVersaoListAdapter(new ArrayList<OSID>(), getActivity());
lView.setAdapter(adpt);
lView.setEmptyView(tela.findViewById(android.R.id.empty));
Bundle id = getArguments();
String get = id.getString("id");
getActivity().setTitle("Versões da OS Nº"+get);
int itinerario = Integer.parseInt(get);
if (isOnline()) {
item = new OSID(itinerario);
(new Carregadados()).execute();
lView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
adpt.getItem(position);
String titulo = ((TextView) view.findViewById(R.id.IDOS)).getText().toString();
String versao = ((TextView) view.findViewById(R.id.textoosfunc)).getText().toString();
Intent intent = new Intent(getActivity(), OS.class);
String IDrestante = titulo.replace("OS Nº ", "");
String Versao = versao.replace("Versão: ", "");
intent.putExtra("id", IDrestante);
intent.putExtra("versao", Versao);
intent.putExtra("tab", "0");
startActivity(intent);
}
});
}
else {
android.app.AlertDialog.Builder alerta = new android.app.AlertDialog.Builder(getActivity());
alerta.setMessage("Você está sem Acesso a Internet por favor verifique suas configurações, ative o wi-fi ou seus dados móveis");
alerta.setPositiveButton("OK", null);
alerta.show();
}
return tela;
}
private boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
private class Carregadados extends AsyncTask<String, Void, List<OSID>> {
private final ProgressDialog dialog = new ProgressDialog(getActivity());
#Override
protected void onPostExecute(List<OSID> result) {
super.onPostExecute(result);
dialog.dismiss();
adpt.setItemList(result);
adpt.notifyDataSetChanged();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setCancelable(false);
dialog.setTitle("Carregando");
dialog.setMessage("Por Favor Aguarde");
dialog.show();
}
#Override
protected List<OSID> doInBackground(String... params) {
List<OSID> result = new ArrayList<OSID>();
ArrayList<NameValuePair> data = new ArrayList<>();
data.add(new BasicNameValuePair("id", String.valueOf(item.OSCodigo)));
HttpParams httprequestparams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httprequestparams, CONNECTION_TIME);
HttpConnectionParams.setSoTimeout(httprequestparams, CONNECTION_TIME) ;
HttpClient cliente = new DefaultHttpClient(httprequestparams);
HttpPost post = new HttpPost(SERVIDOR + "OS/CarregaVersaoOS");
try {
post.setEntity(new UrlEncodedFormEntity(data));
HttpResponse response = cliente.execute(post);
HttpEntity entity = response.getEntity();
String JSONResp = EntityUtils.toString(entity);
JSONArray arr = new JSONArray(JSONResp);
for (int i=0; i < arr.length(); i++) {
result.add(ConvertDados(arr.getJSONObject(i)));
}
return result;
}
catch(Throwable t) {
t.printStackTrace();
}
return null;
}
public OSID ConvertDados(JSONObject obj) throws JSONException {
int oscodigo = obj.getInt("osCodigo");
int versao = obj.getInt("Versao");
String situacao = obj.getString("Situacao");
String finalidade = obj.getString("Finalidade");
String assunto = obj.getString("Assunto");
String previsao = obj.getString("PrevisaoAtendimento");
String solicitadopor = obj.getString("osSolicitadopor");
String solicitacao = obj.getString("Solicitacao");
solicitacao.replace("\r\n","Solicitação não preenchida");
String servico = obj.getString("ServicoExecutado");
String aberto = obj.getString("AbertoPor");
String executado = obj.getString("ExecutadoPor");
int versoes = 0;
return new OSID(oscodigo,versao,versoes,situacao,finalidade,assunto,previsao,solicitadopor,solicitacao,servico,aberto,executado);
}
}
Try this
#Override
public void onBackPressed() {
// call super.onBackPressed(); at last.
Intent intent = new Intent(OS.this, MainActivity.class);
intent.putExtra("position", 2);
startActivity(intent);
super.onBackPressed(); <----
}

Categories

Resources