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"));
}
}
Related
So many people have faced this exception and i tried the solutions available for this exception but none of it actually worked for my case.
So my problem is i have a filter button at my toolbar and it has three items in it 1. ascending order , 2. descending order , 3. date specific. when i am selecting ascending and descending items data is getting populated correctly inside recyclerview. but when i am selecting the date specific option and showing a datepicker ....the data is not getting populated inside recyclerview and when i touch screen application gets crashed and gives me the above mentioned exception.
my code for fragment where i am performing these operations :-
public class PendingOrders extends Fragment {
String filterString="date_desc";
String filterDateString="";
private int mDay,mMonth,mYear;
private static final String TAG = "PendingORDERS";
private RecyclerView mMessagesView;
private List<PendingOrderModel> mMessages = new ArrayList<PendingOrderModel>();
CustomItemClickListener listener;
private PendingOrderAdapter mAdapter;
private Socket mSocket;
private Boolean isConnected = true;
public static final int DIALOG_FRAGMENT = 1;
String actualPrice,amount,total,filledAmount,orderPrice,proceeds,orderDate,orderType,orderId;
String currencyname,order,order1,orderType1 , orderDate1,idz;
public PendingOrders() {
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
mAdapter = new PendingOrderAdapter(context, mMessages,listener);
if (context instanceof Activity) {
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
AppController app = (AppController) getActivity().getApplication();
SharedPreferences pref = getActivity().getSharedPreferences("MyPREFERENCES", 0);
idz=pref.getString("ZuserID", null);
mSocket = app.getSocket();
mSocket.on("pending_orders_data", orderCompletedData);
mSocket.connect();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_pending_orders, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mMessagesView = (RecyclerView) view.findViewById(R.id.rv_pending_orders);
mMessagesView.setLayoutManager(new LinearLayoutManager(getActivity()));
mMessagesView.setItemAnimator(null);
mAdapter = new PendingOrderAdapter(getActivity(), mMessages, new CustomItemClickListener() {
#Override
public void onItemClick(View v, int position) {
String orderid = mMessages.get(position).getmOrderId();
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
Fragment prev = getActivity().getSupportFragmentManager().findFragmentByTag("dialog");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
DialogFragment dialogFrag = PendingCancelDialog.newInstance(123);
dialogFrag.show(getActivity().getFragmentManager().beginTransaction(), "dialog");
Bundle args = new Bundle();
args.putString("ID",orderid);
dialogFrag.setArguments(args);
}
});
mMessagesView.setAdapter(mAdapter);
initObjects();
}
private void initObjects() {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("user_id", idz);
} catch (JSONException e) {
e.printStackTrace();
}
mSocket.emit("register_user", jsonObject.toString());
mSocket.emit("fetch_pending_orders", getSendMessageString(""));
}
public String getSendMessageString(String message) {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("page_no", "1"); //1: text message 2: multimedia message
jsonObject.put("user_id", idz);
jsonObject.put("records_per_page", "5");
jsonObject.put("filter", filterString);
Log.i("??", "filterString: "+filterString);
jsonObject.put("filter_date", filterDateString);
Log.i("??", "filterDateString: "+filterDateString);
return jsonObject.toString();
} catch (Exception e) {
e.printStackTrace();
}
return message;
}
private void addMessage(String orderId,String order,String currencyname,String amount,String filledAmount,String proceeds,String orderPrice,String orderDate,String orderType) {
mMessages.add(new PendingOrderModel.Builder(PendingOrderModel.RECEIVER)
.orderid(orderId).order(order).amount(amount).currencyname(currencyname).filledamount(filledAmount).orderprice(orderPrice).proceeds(proceeds).orderdate(orderDate).ordertype(orderType).build());
mMessagesView.getRecycledViewPool().clear();
mAdapter.notifyDataSetChanged();
}
private Emitter.Listener orderCompletedData = new Emitter.Listener() {
#Override
public void call(final Object... args) {
if(getActivity() != null) {
getActivity().runOnUiThread(() -> {
JSONArray object1 = (JSONArray) args[0];
if(object1 != null){
JSONArray array = new JSONArray();
array = object1.optJSONArray(0);
int arraylength = array.length();
for(int j=0; j<array.length();j++){
JSONObject obj = new JSONObject();
try {
obj = array.getJSONObject(j);
currencyname = obj.getString("coin");
orderId = obj.getString("id");
order1 = obj.getString("order");
filledAmount = obj.getString("coin_quantity");
amount = obj.getString("total_amount");
proceeds = obj.getString("remaining");
orderPrice = obj.getString("order_price");
orderDate1 = obj.getString("create_time");
orderType1= obj.getString("order_type");
} catch (JSONException e) {
e.printStackTrace();
}
if(order1 == "1"){
order = "Limit";
}
else{
order = "Market";
}
if(orderType1 == "1"){
orderType = "Sell";
}else{
orderType = "buy";
}
String [] date = orderDate1.split("T");
orderDate = date[0].trim();
addMessage(orderId,order,currencyname,amount,filledAmount,proceeds,orderPrice,orderDate,orderType);
}
}
});
}
}
};
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.asc_order:
filterString="date asc";
filterDateString="";
mMessages.clear();
mSocket.emit("fetch_pending_orders", getSendMessageString(""));
return true;
case R.id.desc_order:
filterString="date desc";
mMessages.clear();
mSocket.emit("fetch_pending_orders", getSendMessageString(""));
return true;
case R.id.pick_date:
filterString="date specific";
mMessages.clear();
pickdate();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void pickdate() {
Calendar c1 = Calendar.getInstance();
mYear = c1.get(Calendar.YEAR);
mMonth = c1.get(Calendar.MONTH);
mDay = c1.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(),R.style.DAte_Theme,
(view, year, monthOfYear, dayOfMonth) -> {
int month = monthOfYear + 1;
String formattedMonth = "" + month;
String formattedDayOfMonth = "" + dayOfMonth;
if(month < 10){
formattedMonth = "0" + month;
}
if(dayOfMonth < 10){
formattedDayOfMonth = "0" + dayOfMonth;
}
filterDateString= formattedDayOfMonth + "/" + formattedMonth + "/" + year;
Log.i("date",filterDateString);
mSocket.emit("fetch_pending_orders", getSendMessageString(""));
// updateDate(filterDateString);
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
}
Below is my Logcat :-
java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder{cfdb59c position=3 id=-1, oldPos=-1, pLpos:-1 no parent} android.support.v7.widget.RecyclerView{476168c VFED..... .F...... 0,0-1080,1560 #7f090169 app:id/rv_pending_orders}, adapter:com.vamediabox.greenpay.adapters.PendingOrderAdapter#d6e71d5, layout:android.support.v7.widget.LinearLayoutManager#e738dea, context:com.vamediabox.greenpay.activities.MyorderActivity#70a64f9
at android.support.v7.widget.RecyclerView$Recycler.validateViewHolderForOffsetPosition(RecyclerView.java:5421)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5603)
at android.support.v7.widget.GapWorker.prefetchPositionWithDeadline(GapWorker.java:285)
at android.support.v7.widget.GapWorker.flushTaskWithDeadline(GapWorker.java:342)
at android.support.v7.widget.GapWorker.flushTasksWithDeadline(GapWorker.java:358)
at android.support.v7.widget.GapWorker.prefetch(GapWorker.java:365)
at android.support.v7.widget.GapWorker.run(GapWorker.java:396)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
See just do one thing when you select the date picker then add these lines before calling the main function.
onClick
{
adapter.notifyDataSetChanged();
recyclerView.getRecycledViewPool().clear();
and then the rest code....
}
Here's my java from 'different java file' :
public class MainPage extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
ArrayList<HashMap<String, String>> Item_List;
TabLayout tabLayout;
ViewPageAdapter viewPageAdapter;
ViewPager viewPager;
ImageView pfp;
ProgressDialog PD_three;
Bitmap bitmap;
TextView usernameToolbar;
Intent postActivity;
Bitmap cropImg;
private int PICK_IMAGE_REQUEST = 1;
private String KEY_IMAGE = "ProfilePicture";
private String KEY_NAME = "Name";
private String KEY_USERTOKEN = "UserToken";
private String UserToken;
final int CROP_PIC_REQUEST_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page);
initTypeface();
PD_three = new ProgressDialog(this);
PD_three.setCancelable(false);
PD_three.setTitle("Please Wait...");
PD_three.setMessage("Retrieving Data from Database...");
getProfileInfo();
String username = getIntent().getStringExtra("Username");
TextView tv = (TextView) findViewById(R.id.usernameND);
tv.setText(username);
//id's
pfp = (ImageView) findViewById(R.id.imageView_one);
//SearchIntent
Intent searchI = getIntent();
if (Intent.ACTION_SEARCH.equals(searchI.getAction())) {
String query = searchI.getStringExtra(SearchManager.QUERY);
Toast.makeText(MainPage.this, query, Toast.LENGTH_SHORT).show();
}
//Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(null);
//Tabs
tabLayout = (TabLayout) findViewById(R.id.tablayout_two);
viewPager = (ViewPager) findViewById(R.id.viewPager_two);
viewPageAdapter = new ViewPageAdapter(getSupportFragmentManager());
viewPageAdapter.addFragments(new FeedFragment(), "Feed");
viewPageAdapter.addFragments(new MessagesFragment(), "Messages");
viewPageAdapter.addFragments(new NotificationsFragment(), "Notifications");
viewPager.setAdapter(viewPageAdapter);
tabLayout.setupWithViewPager(viewPager);
//NavigationDrawer
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.profile) {
Intent i = new Intent(this, Profile.class);
startActivity(i);
} else if (id == R.id.whatshot) {
Intent i = new Intent(this, WhatsHot.class);
startActivity(i);
} else if (id == R.id.trending) {
Intent i = new Intent(this, Trending.class);
startActivity(i);
} else if (id == R.id.radioplayer) {
Intent i = new Intent(this, Radio.class);
startActivity(i);
} else if (id == R.id.musicplayer) {
Intent i = new Intent(this, MusicPlayer.class);
startActivity(i);
} else if (id == R.id.settings) {
Intent i = new Intent(this, Settings.class);
startActivity(i);
} else if (id == R.id.info) {
Intent i = new Intent(this, Info.class);
startActivity(i);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
SearchView searchView = (SearchView) menu.findItem(R.id.search_view).getActionView();
SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
return super.onCreateOptionsMenu(menu);
}
//ImageInfo
//Typeface
private void initTypeface() {
Typeface myTypeface = Typeface.createFromAsset(getAssets(), "fonts/Amble-Regular.ttf");
TextView text = (TextView) findViewById(R.id.toolbarTitle);
text.setTypeface(myTypeface);
myTypeface = Typeface.createFromAsset(getAssets(), "fonts/Amble-Regular.ttf");
text = (TextView) findViewById(R.id.usernameND);
text.setTypeface(myTypeface);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.v(MainPage.class.getSimpleName(), "hey=" + requestCode + resultCode);
if (resultCode == CROP_PIC_REQUEST_CODE || resultCode == 2 || resultCode == -1) {
if (requestCode == CROP_PIC_REQUEST_CODE) {
if (data != null) {
Bundle extras = data.getExtras();
Bitmap image = extras.getParcelable("data");
pfp.setImageBitmap(image);
UploadImage();
bitmap = image;
}
}
}
}
private void getProfileInfo() {
Intent I = getIntent();
String Uname = I.getStringExtra("Username");
final String Username = Uname.replaceAll("\\s", "");
RequestQueue queue = Volley.newRequestQueue(MainPage.this);
PD_three.show();
String UPLOAD_URL = "http://10.0.0.177/Echo/ServerFilesApp/GetProfileInfo.php?Username=" + Username;
StringRequest stringRequest = new StringRequest(Request.Method.GET, UPLOAD_URL, new Response.Listener<String>() {
#Override
public Bitmap onResponse(String response) {
PD_three.dismiss();
UserToken = response;
getProfilePicture();
return null;
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
PD_three.dismiss();
Toast.makeText(MainPage.this, error.toString(), Toast.LENGTH_LONG).show();
}
});
queue.add(stringRequest);
}
private void getProfilePicture() {
PD_three.show();
RequestQueue queue = Volley.newRequestQueue(MainPage.this);
String IMAGE_URL = "http://10.0.0.177/Echo/Users/" + UserToken + "/ProfilePicture.jpg";
pfp = (ImageView) findViewById(R.id.imageView_one);
ImageRequest request = new ImageRequest(IMAGE_URL,
new Response.Listener<Bitmap>() {
#Override
public Bitmap onResponse(Bitmap bitmap) {
cropImg = Bitmap.createBitmap(bitmap, 0, 0, 99, 99);
pfp.setImageBitmap(cropImg);
PD_three.dismiss();
return cropImg;
}
}, 0, 0, ImageView.ScaleType.FIT_CENTER, Bitmap.Config.RGB_565,
new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
PD_three.dismiss();
pfp.setImageResource(R.drawable.ic_user_b);
Toast.makeText(MainPage.this, "Error on retrieving profile pic.", Toast.LENGTH_LONG).show();
}
});
queue.add(request);
}
private void UploadImage() {
RequestQueue queue = Volley.newRequestQueue(MainPage.this);
String UPLOAD_URL = "http://10.0.0.177/Echo/ServerFilesApp/UpdateProfilePicture.php";
PD_three.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
new Response.Listener<String>() {
#Override
public Bitmap onResponse(String response) {
// getProfilePicture();
PD_three.dismiss();
Log.v(MainPage.class.getSimpleName(), "hey=hey");
getProfilePicture();
return null;
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
PD_three.dismiss();
Toast.makeText(MainPage.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
String Image = getImageUri(bitmap);
String Name = UserToken + "/ProfilePicture";
Map<String, String> params = new Hashtable<String, String>();
params.put(KEY_IMAGE, Image);
params.put(KEY_NAME, Name);
params.put(KEY_USERTOKEN, UserToken);
return params;
}
};
queue.add(stringRequest);
}
public String getImageUri(Bitmap bmp) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
public void postClick(View view) {
Intent I = getIntent();
String Uname = I.getStringExtra("Username");
final String Username = Uname.replaceAll("\\s", "");
//COMPRESS PFP
ByteArrayOutputStream stream = new ByteArrayOutputStream();
cropImg.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
postActivity = new Intent(MainPage.this, PostFragment.class);
postActivity.putExtra("UserToken", UserToken);
postActivity.putExtra("Username", Username);
postActivity.putExtra("profilePicture", byteArray);
MainPage.this.startActivity(postActivity);
//MainPage.this.overridePendingTransition(R.anim.slide_down, R.anim.slide_up);
}
public void onPfpClick(View view) {
Intent cropImage = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
cropImage.putExtra("crop", "true");
cropImage.putExtra("aspectX", 1);
cropImage.putExtra("aspectY", 1);
cropImage.putExtra("outputX", 100);
cropImage.putExtra("outputY", 100);
cropImage.putExtra("return-data", true);
setResult(RESULT_OK, cropImage);
startActivityForResult(cropImage, CROP_PIC_REQUEST_CODE);
}
private String Username() {
String Username = getIntent().getStringExtra("Username");
return Username;
}
}
Here's my fragment java code:
public class FeedFragment extends Fragment {
private static final String TAG = FeedFragment.class.getSimpleName();
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
String UsernamePast;
String UserTokenPast;
Cache cache;
Entry entry;
String URL_FEED;
#SuppressLint("NewApi")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_feed, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ListView listView = (ListView) getView().findViewById(R.id.FeedContentList);
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(getContext(), feedItems);
listView.setAdapter(listAdapter);
// We first check for cached request
cache = AppController.getInstance().getRequestQueue().getCache();
URL_FEED = "http://10.0.0.177/Echo/ServerFilesApp/feed.json";
entry = cache.get(URL_FEED);
getFeedContent();
}
public void getFeedContent() {
if (entry != null) {
// fetch the data from cache
try {
String data = new String(entry.data, "UTF-8");
try {
parseJsonFeed(new JSONObject(data));
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else {
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
URL_FEED, null, new Response.Listener<JSONObject>() {
#Override
public Bitmap onResponse(JSONObject response) {
VolleyLog.d(TAG, "Response: " + response.toString());
Log.v(TAG, "hey=" + "heu");
if (response != null) {
parseJsonFeed(response);
}
return null;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
}
/**
* Parsing json response and passing the data to feed view list adapter
*/
private void parseJsonFeed(JSONObject response) {
try {
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
FeedItem item = new FeedItem();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
// Image might be null sometimes
String image = feedObj.isNull("image") ? null : feedObj
.getString("image");
item.setImage(image);
item.setStatus(feedObj.getString("status"));
item.setProfilePicture(feedObj.getString("profilePic"));
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedURL = feedObj.isNull("url") ? null : feedObj
.getString("url");
item.setURL(feedURL);
item.setLitBackground(R.drawable.fire);
feedItems.add(item);
}
FeedItem item2 = new FeedItem();
item2.setId(0);
item2.setName("SORRY");
// Image might be null sometimes
item2.setImage(null);
item2.setStatus("This Is Everything there is for Now. Refresh to get More Content");
item2.setProfilePicture(null);
item2.setTimeStamp(null);
item2.setURL(null);
feedItems.add(item2);
// notify data changes to list adapter
listAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onResume() {
super.onResume();
getFeedContent();
}
#Override
public void onPause() {
super.onPause();
cache.clear();
}
}
To go more in depth, what I'm trying to figure out is how can I refresh a fragment from a different java file?
Our objective is to have feed like Facebook but it doesn't load the posts we post. How will that be possible? (preferably using Google Volley request, if possible)
If different java file is the container activity of fragment, then that activity must have the reference of that particular fragment, you can control the fragment with this instance easily. But make sure that when when you will show this fragment, then the instance you used in activity, that instance is used for showing otherwise what you have changed in the fragment you won't get that update. your code is for fragments:
tabLayout = (TabLayout) findViewById(R.id.tablayout_two);
viewPager = (ViewPager) findViewById(R.id.viewPager_two);
viewPageAdapter = new ViewPageAdapter(getSupportFragmentManager());
viewPageAdapter.addFragments(new FeedFragment(), "Feed");
viewPageAdapter.addFragments(new MessagesFragment(), "Messages");
viewPageAdapter.addFragments(new NotificationsFragment(), "Notifications");
viewPager.setAdapter(viewPageAdapter);
tabLayout.setupWithViewPager(viewPager);
Here new instance of fragments are being created every time. According to your demands this should be:
FeedFragment feedFragment = new FeedFragment();
MessagesFragment messagesFragment = new MessagesFragment();
NotificationFragment notifyFragment = new NotificationFragment();
tabLayout = (TabLayout) findViewById(R.id.tablayout_two);
viewPager = (ViewPager) findViewById(R.id.viewPager_two);
viewPageAdapter = new ViewPageAdapter(getSupportFragmentManager());
viewPageAdapter.addFragments(feedFragment, "Feed");
viewPageAdapter.addFragments(messagesFragment, "Messages");
viewPageAdapter.addFragments(notifyFragment, "Notifications");
viewPager.setAdapter(viewPageAdapter);
tabLayout.setupWithViewPager(viewPager);
Now with the references of fragment, you can do whatever you want to the fragment. Here in the above code snippet the references are local variable, you can make it global and access this reference from wherever you want in the activity.
Still if you have any question, let me know.
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);
}
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.
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(); <----
}