I did a quick search in here and didn't find any answers for my qustion, if its already answered please point me to that question ..
I have an ActionBar Tabs with swipe views implemented according to this android training. My activity have 3 tabs
Weather Comment Dashboard
and these fragments
WeatherFragment CommentsFragment LoginFragment DasboardFragment RegisterFragment
As the activity is started,
Weather Tab displays WeatherFragment ,
Comments Tab displays CommentsFragment and
Dashboard Tab displays LoginFragment
If Login is successful in LoginFragment, DasboardFragment should replace the LoginFragment inside the Dashboard Tab. So if user swipes to other tabs and come back to Dashboard Tab DasboardFragment should be visible.
I'm new to android development, so any code snippets or tutorial would be greatly appreciated
Code i've so far MainActivity class
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
AppSectionsPagerAdapter mAppSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_network_weather);
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(
getSupportFragmentManager());
final ActionBar actionBar = getActionBar();
//actionBar.setDisplayShowTitleEnabled(false);
//actionBar.setDisplayShowHomeEnabled(false);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(actionBar.newTab()
.setText(mAppSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
return new WeatherInfoFragment();
case 1:
return new PostsFragment();
default: //TODO method to find which fragment to display ?
return new LoginFragment();
}
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
if (position == 0) {
return "Weather";
} else if (position == 1){
return "Comments";
}
else{
return "Dashboard";
}
}
}
#Override
public void onTabReselected(ActionBar.Tab tab,
android.app.FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {
}
}
LoginFragment
public class LoginFragment extends Fragment implements AsyncResponse {
Button loginButton;
TextView loginError, login_url;
JSONfunctions task;
JSONObject jsonObject;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.login, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onStart() {
super.onStart();
loginButton = (Button) getView().findViewById(R.id.button_login);
loginError = (TextView) getView().findViewById(R.id.login_error);
loginButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
attemptLogin(finalLoginUrl);
// attemptPost(postURL);
}
});
}
private void attemptLogin(String url) {
try {
task = new JSONfunctions(getActivity());
task.listener = this;
task.execute(new String[] { url });
} catch (Exception ex) {
Log.e("attempt login", ex.getMessage());
}
}
}
#Override
public void processFinish(String result) {
try {
jsonObject = new JSONObject(result);
int success = Integer.parseInt(jsonObject.getString("Success"));
if (success == 0) {
// Replace LoginFragment and launch DashboardFragment ?
} else {
loginError.setText(jsonObject.getString("ErrorMessage"));
}
} catch (JSONException e) {
Log.e("JSON parsing from login result", e.getMessage());
}
}
}
I'm not sure this is the best way to handle this but you could define a static boolean inside your MainActivity like so:
public static boolean loggedIn = false;
(e.g. below ViewPager mViewPager;)
And then, in your method processFinish(...) inside the LoginFragment when success is 0 just set MainActivity.loggedIn = true;
This way you can simply put in an if-statement inside your default-case in getItem-method to check whether the user is logged in (if so call the Dashboard-Fragment) or not (display Login-Fragment).
Hope this works for you!
Edit: LoginFragment
public class LoginFragment extends Fragment implements AsyncResponse {
Button loginButton;
TextView loginError, login_url;
JSONfunctions task;
JSONObject jsonObject;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.login, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onStart() {
super.onStart();
loginButton = (Button) getView().findViewById(R.id.button_login);
loginError = (TextView) getView().findViewById(R.id.login_error);
loginButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
attemptLogin(finalLoginUrl);
// attemptPost(postURL);
}
});
}
private void attemptLogin(String url) {
try {
task = new JSONfunctions(getActivity());
task.listener = this;
task.execute(new String[] { url });
} catch (Exception ex) {
Log.e("attempt login", ex.getMessage());
}
}
#Override
public void processFinish(String result) {
try {
jsonObject = new JSONObject(result);
int success = Integer.parseInt(jsonObject.getString("Success"));
if (success == 0) {
MainActivity.loggedIn = true;
} else {
loginError.setText(jsonObject.getString("ErrorMessage"));
}
} catch (JSONException e) {
Log.e("JSON parsing from login result", e.getMessage());
}
}
}
Was my own fault for not reading the answer here thoroughly. Implemented the code from that answer and got the functionality working :)
Related
I'm new to this concept. I read several threads but I block so thanks in advance for your patience!
In a fragment (frag1) I launch an async task. I want to prevent the user of doing anything while the task is not completed so I want to communicate the % of the task completed so the user waits informed.
I've defined an interface in a java SetVal.java:
interface SetVal {
void setVal(int val);
}
My async task:
class AsyncCounter extends AsyncTask<Void, Integer, Void> {
private SetVal sender;
public AsyncCounter(SetVal sv){
this.sender = sv;
}
#Override
protected Void doInBackground(Void... params) {
for(int i=0;i<60;i++){
publishProgress(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
Log.i("ASYNC TASK","val: "+values[0]);
sender.setVal(values[0]);
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
public interface SetVal {
public void setVal(int val);
}
public void setListener(SetVal listener) {
this.sender = listener;
}
}
I'm struggling to know how to pass the interface to the task.
Is my code correct?
How do I instantiate the async task?
fragment:
public class Frag1 extends android.app.Fragment implements SetVal {
private static TextView txt;
private int counter;
SetVal listener;
public Frag1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_frag1, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
txt = (TextView) getActivity().findViewById(R.id.txt);
Button btn = (Button) getActivity().findViewById(R.id.btn1);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.i("Frag1", "val: " + counter);
if (counter > 0) return;
FragmentTransaction ft = getFragmentManager().beginTransaction();
Frag2 f2 = new Frag2();
ft.replace(R.id.content_frame, f2);
ft.addToBackStack("f2");
ft.commit();
}
});
Button btn2 = (Button) getActivity().findViewById(R.id.btn2);
btn2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AsyncCounter ac = new AsyncCounter(???????);
ac.execute();
}
});
}
#Override
public void setVal(int val) {
counter = val;
}
}
Not sure what and why you are trying to do that, but you can pass the Fragment :
Try to create a private method:
public void onClick(View v) {
startMyAsync();
}
private void startMyAsync() {
new AsyncCounter(this).execute();
}
finally:
public AsyncCounter(Frag1 context){
this.sender = (SetVal)context;
}
I have two tabs which contain two different fragments. Tab1 for fragment1 and tab2 for fragment2. From fragment1, I want to pass a string value in fragment2's TextView by clicking on a Button.
However, the UI of fragment2 is not being updated. Sample code has given below.
In MainActivity :
private Fragment1 fragment1;
private Fragment2 fragment2;
private TabLayout tabLayout;
protected void onCreate(Bundle savedInstanceState) {
fragment1 = new Fragment1();
fragment2 = new Fragment2();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_holder, fragment1).commit();
tabLayout = (TabLayout) findViewById(R.id.tab);
tabLayout.getTabAt(0).select();
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
if (tab.getPosition() == 0) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_holder, fragment1).commit();
} else if (tab.getPosition() == 1) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_holder, fragment2).commit();
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
}
}
public void showFragment2(final String data) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_holder, fragment2).commit();
tabLayout.getTabAt(1).select();
if (!TextUtils.isEmpty(data)) {
if (fragment2 != null) {
fragment2.setData(data);
}
}
}
In Fragment1 :
private Button button;
protected void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
button = (Button) view.findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity)getActivity()).showFragment2("Updated Data");
}
});
}
In Fragment2 :
private TextView tv;
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
tv = (TextView) view.findViewById(R.id.tv);
}
public void setData(String data){
tv.setText(data);
}
Important Update:
If I update the UI in Handler. Then it works. But, seems it's not the proper way.
handler.postDelayed(new Runnable() {
#Override
public void run() {
tabLayout.getTabAt(1).select();
if(!TextUtils.isEmpty(data)){
if(fragment2 != null){
fragment2.setData(data);
}
}
}
},500);
Use .executePendingTransactions() which would work synchronously along with .commit() which works Asynchronously.
After a FragmentTransaction is committed with
FragmentTransaction.commit(), it is scheduled to be executed
asynchronously on the process's main thread. If you want to
immediately executing any such pending operations, you can call this
function (only from the main thread) to do so. Note that all callbacks
and other related behavior will be done from within this call, so be
careful about where this is called from.
DO:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_holder, fragment2).commit();
getSupportFragmentManager().executePendingTransactions();
tabLayout.getTabAt(1).select();
if(!TextUtils.isEmpty(data)){
if(fragment2 != null){
fragment2.setData(data);
}
}
Hey hi i am not sure but try this:
public void showFragment2(final String data) {
if (!TextUtils.isEmpty(data)) {
if (fragment2 != null) {
// fragment2.setData(data);
Bundle arguments = new Bundle();
arguments.putString( "string_key" , data);
fragment2.setArguments(arguments);
}
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_holder, fragment2).commit();
tabLayout.getTabAt(1).select();
}
and In Fragment2 :
private TextView tv;
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Bundle arguments = getArguments();
String desired_string = arguments.getString("string_key");
tv = (TextView) view.findViewById(R.id.tv);
setData(desired_string);
}
public void setData(String data){
tv.setText(data);
}
set the data in activity method from fragment 1 and while loading fragment get the data from activity and set it in fragment 2
mainActivity(){
string fragment1Data;
public void setFragment1Data(string data){
fragment1Data = data;
}
public string getFragment1Data(){
return fragment1Data
}
}
in Fragment 1
private Button button;
protected void onViewCreated(View view, #Nullable Bundle savedInstanceState)
{
button = (Button) view.findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity)getActivity()).showFragment2("Updated Data");
((MainActivity)getActivity()).setFragment1Data("data");
}
});
}
in Fragment 2
private TextView tv;
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
tv = (TextView) view.findViewById(R.id.tv);
tv.setText(((MainActivity)getActivity()).getFragment1Data());
}
I have navigationdrawer with nav menus. When clicking on each nav menus, specific fragment opened. Each fragment display recylerviews who fetch data from SQLite external database.Now when open new fragment, little seconds must wait and when to click on each item for go to next activity for display details information about the item, 5 seconds must wait to open Details Activity. I know this is a problem for fetching data in main Thread and fetch bitmap in the main thread.But I don't know how to solve this problem with use AsyncTask.My big problem is an open new activity for display information and waiting for 5 seconds.
This is my asiafragment.
AsiaFragment
public class AsiaFragment extends Fragment {
private static final String ASIA_FRAGMENT = "asia_fragment";
ArrayList<AsiaCountry> asiaCountries = new ArrayList<>();
ContentAdapter contentAdapter;
RecyclerView recyclerView;
private boolean isListView;
private Menu menu;
private StaggeredGridLayoutManager staggeredGridLayoutManager;
private MyAsyncTas myAsyncTas;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.asia_fragment, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
getActivity().setTitle("Asia");
isListView = true;
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
new MyAsyncTas().execute();
}
// When click on grid icon, view items must be convert to grid.
public void toggle() {
MenuItem item = menu.findItem(R.id.grid);
if (isListView) {
staggeredGridLayoutManager.setSpanCount(2);
item.setIcon(R.drawable.ic_vertical);
item.setTitle("Show as list");
isListView = false;
} else {
staggeredGridLayoutManager.setSpanCount(1);
item.setIcon(R.drawable.ic_grid);
item.setTitle("Show grid");
isListView = true;
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.grid_item, menu);
this.menu = menu;
Log.d("Menu created", "grid");
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.grid) {
Toast.makeText(getActivity(), "Grid item touched", Toast.LENGTH_SHORT).show();
toggle();
return true;
}
if (id == R.id.settings) {
Toast.makeText(getActivity(), "Setting clicked", Toast.LENGTH_SHORT).show();
return true;
}
return onOptionsItemSelected(item);
}
// When loading AsiaFragment, database loading from Eternal database.
public void loadDataBase() {
WorldCountryDatabase worldCountryDatabase = new WorldCountryDatabase(getActivity());
try {
worldCountryDatabase.createDatabase();
worldCountryDatabase.openDataBase();
Log.d("TAG", "Database open");
} catch (SQLiteException o) {
o.printStackTrace();
Log.d("Tag", o.getMessage());
}
try {
// Tell to database , take name and viewImage from worldCountries .
Cursor cursor = worldCountryDatabase.QueryData("SELECT name, Image FROM country WHERE continent ='آسیا'");
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
AsiaCountry asiaCountry = new AsiaCountry();
asiaCountry.setName(cursor.getString(0));
asiaCountry.setFlag(cursor.getString(1));
Log.d(ASIA_FRAGMENT, cursor.getString(1));
asiaCountries.add(asiaCountry);
} while (cursor.moveToNext());
worldCountryDatabase.close();
}
}
} catch (SQLiteException o) {
o.printStackTrace();
Log.d("TAG", o.getMessage());
}
// When loading RecylerView staggeredGridLayout loading.
staggeredGridLayoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
contentAdapter = new ContentAdapter(getActivity(), asiaCountries);
contentAdapter.notifyDataSetChanged();
contentAdapter.setListener(new ContentAdapter.Listener() {
#Override
public void onClick(int position) {
}
});
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(staggeredGridLayoutManager);
recyclerView.setAdapter(contentAdapter);
}
public class MyAsyncTas extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
return true;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
loadDataBase();
}
}
This is my DetailCountry fragment, who must be displayed detatail country clicked.
DetailsCountry
public class DetailsCountry extends AppCompatActivity implements
TabLayout.OnTabSelectedListener,
EconomicFragment.EconomicOnFragmentInteractionListener,
SummarizeFragment.SummarizeOnFragmentInteractionListener,
HistoryFragment.HistoryOnFragmentInteractionListener,
GeographyFragment.GeographyOnFragmentInteractionListener,
TipsFragment.TipsOnFragmentInteractionListener,
DescriptionFragment.OtherOnFragmentInteractionListener,
PeopleFragment.PeopleOnFragmentInteractionListener {
public static String NAME_COUNTRY = "name";
public final String pageTitle[] = {"خلاصه",
"تاریخ",
"جغرافی",
"اقتصاد",
"مردم",
"غیره",
"نکات"};
ArrayList<AsiaCountry> asiaList = new ArrayList<>();
ImageView imageHistory;
TabLayout tabLayout;
ViewPager viewPager;
String content;
Bundle bundle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detial_country);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_details);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
viewPager = (ViewPager) findViewById(R.id.viewPager_detail_country);
tabLayout = (TabLayout) findViewById(R.id.tabLayout_detail_country);
imageHistory = (ImageView) findViewById(R.id.image_detail_country);
bundle = getIntent().getExtras();
if (bundle != null) {
content = bundle.getString("name");
Log.d("contentDetail", content);
}
// Set title for activity title.
getSupportActionBar().setTitle(content);
retrieveData();
if (asiaList != null && asiaList.size() > 0) {
for (int i = 0; i < asiaList.size(); i++) {
imageHistory.setImageBitmap(loadBitmapFromAssets(getApplicationContext(),
asiaList.get(i).getImageResourceID()));
}
}
int numberPage = 7;
for (int i = 0; i < numberPage; i++) {
tabLayout.addTab(tabLayout.newTab().setText(pageTitle[i]));
}
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
ViewPagerCountryAdapter viewPagerAdapter = new ViewPagerCountryAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(this);
}
private void retrieveData() {
WorldCountryDatabase worldCountryDatabase = new WorldCountryDatabase(getApplicationContext());
worldCountryDatabase.createDatabase();
worldCountryDatabase.openDataBase();
Log.d(ARG_PARAM1, "Database opened");
try {
Cursor cursor = worldCountryDatabase.QueryData("SELECT viewImage FROM country WHERE name = '" + content + "'");
Log.d("CURSOR", cursor.toString());
if (cursor.moveToFirst()) {
do {
AsiaCountry asia = new AsiaCountry();
asia.setImageResourceID(cursor.getString(0));
Log.d("image", cursor.getString(0));
asiaList.add(asia);
} while (cursor.moveToNext());
cursor.close();
}
} catch (SQLException e) {
e.printStackTrace();
Log.d("TAG", e.getMessage());
}
}
#Nullable
private Bitmap loadBitmapFromAssets(Context context, String path) {
InputStream stream = null;
try {
stream = context.getAssets().open(path);
return BitmapFactory.decodeStream(stream);
} catch (Exception ignored) {
} finally {
try {
if (stream != null) {
stream.close();
}
} catch (Exception ignored) {
}
}
return null;
}
#Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(base));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
#Override
public void economiOnFragmentInteraction(Uri uri) {
}
#Override
public void tipsOnFragmentInteraction(Uri uri) {
}
#Override
public void otherOnFragmentInteraction(Uri uri) {
}
#Override
public void peopleOnFragmentInteraction(Uri uri) {
}
#Override
public void historyOnFragmentInteraction(Uri uri) {
}
#Override
public void geographyOnFragmentInteraction(Uri uri) {
}
#Override
public void summarizeOnFragmentInteraction(Uri uri) {
}
public class DetailTask extends AsyncTask<Void, Void, Boolean>{
#Override
protected Boolean doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
}
}
Please help me, good friends. Thanks
I can read and write TCP/IP buffer on the Main layout and MainActivity java with a button.
But can't do so on different fragment or different layout.
ERROR MESSAGE IS:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.murat.ev.TcpClient.sendMessage(java.lang.String)' on a null object reference
My code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
public TcpClient mTcpClient;
public Thread send_data;
public Button button;
public byte data[]=new byte[1024];
public DatabaseConstruction db;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DatabaseConstruction(getApplicationContext());
new datasync().execute("");
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment1 fragment1=new Fragment1();
fragmentTransaction.replace(R.id.container, fragmen1_layout);
fragmentTransaction.commit();
button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
send_data_pre();
}
});
}
public class datasync extends AsyncTask<String, String, TcpClient>
{
#Override
protected TcpClient doInBackground(String... message)
{
//we create a TCPClient object and
mTcpClient = new TcpClient(new TcpClient.OnMessageReceived()
{
#Override
//here the messageReceived method is implemented
public void messageReceived(String message)
{
Log.i("Debug","Input message: " + message);
publishProgress(message);
}
});
mTcpClient.run();
return null;
}
#Override
protected void onProgressUpdate(String... values)
{
super.onProgressUpdate(values);
Log.i("onProgressUpdate",values[0]);
}
}
public void send_data_pre()
{
send_data = new Thread(new send_data("hello"));
send_data.start();
}
public class send_data implements Runnable
{
private String message;
public send_data (String message)
{
this.message = message;
}
#Override
public void run()
{
mTcpClient.sendMessage(message);
Log.i("Debug", "mesaj did send");
}
}
}
Fragment1.java
public class Fragment1 extends Fragment {
Button button1;
MainActivity main=new MainActivity();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment1_layout, container, false);
button1 =(Button)view.findViewById(R.id.buton_1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
main.send_data(); ////THIS HERE IS APP STOP AND ERROR
}
});
return view;
}
}
maybe in fragment you want to do
main.send_data_pre(); insted of
main.send_data();
like you do in OnCreate() of the MainActivity if i understood your question well.
I'm Using viewpager with 2 swiping tab layouts. In the first tablayout I post data to the server and when I switch the tab the Listview in not update. Only when I click on Listview Item and close it the Listview gets refreshed and the posted data is visible...
Question Is : How to automatically refresh Listview when data is posted to server can some one help please.
public class PagerAdapter extends FragmentStatePagerAdapter {
int numOfTabs;
public PagerAdapter(FragmentManager fm,int numOfTabs) {
super(fm);
this.numOfTabs=numOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
RaiseComplaintFragment RFragment=new RaiseComplaintFragment();
return RFragment;
case 1:
ComplaintListFragment CFragment=new ComplaintListFragment();
return CFragment;
default:
return null;
}
}
#Override
public int getCount() {
return numOfTabs;
}
}
This is the method which posts data to the server
public void postDataToServer(String complaintdata) throws JSONException {
String url = URLMap.getPostComplaintUrl();
String roleId = LoggedInUserStore.getLoggedInRoleId(getContext());
String branchId = LoggedInUserStore.getLoggedInBranchId(getContext());
String compid = LoggedInUserStore.getLoggedInCompanyId(getContext());
HashMap<String, String> params = new HashMap<>();
params.put("CallRecordID", "0"); //pass 0 if we are inserting a new record always
params.put("CompanyID", compid);
params.put("BranchID", branchId);
params.put("ServiceID", sId);
params.put("CallLocationID", lId);
params.put("RaisedByID", roleId);
params.put("ComplaintDetails", complaintdata);
params.put("CallStatusID", "1");
pDialog = new ProgressDialog(getContext());
pDialog.setMessage("Please wait..");
pDialog.setProgressStyle(pDialog.STYLE_SPINNER);
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
JsonObjectRequest req = new JsonObjectRequest(url, new JSONObject(params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Complaint has been registered successfully");
builder.setMessage("").setCancelable(true);
AlertDialog alertDialog = builder.create();
alertDialog.show();
_complaintText.setText("");
serviceSpinner.setSelection(0);
locationSpinner.setSelection(0);
pDialog.dismiss();
/*((HomeActivity)getActivity()).getViewPager().setCurrentItem(1); //onCLick of Submit it just switches the tab
String tagName="android:switcher:"+R.id.pager+":"+1;
ComplaintListFragment f2=(ComplaintListFragment)getActivity().getSupportFragmentManager().findFragmentByTag(tagName);
f2.fetchComplaintData();*/
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Unable to register your request.\nPlease try later.");
builder.setCancelable(true);
AlertDialog alertDialog = builder.create();
alertDialog.show();
pDialog.dismiss();
}
});
req.setRetryPolicy(new VolleyRetryPolicy().getRetryPolicy());
RequestQueue requestQueue = ((VolleyRequestQueue) getActivity().getApplication()).getRequestQueue();
requestQueue.add(req);
}
My HomeActivity class which handles two tab layouts
viewPager = (ViewPager) findViewById(R.id.view_Pager);
tabLayout = (TabLayout) findViewById(R.id.tab_Layout);
String roleID = LoggedInUserStore.getLoggedInRoleId(getApplicationContext());
if (roleID.equals("4")) {
//RAISE COMPLAINT UI. IF ROLE ID == 4 MANAGER DASHBOARD
tabLayout.addTab(tabLayout.newTab().setText("Raise Complaint"));
tabLayout.addTab(tabLayout.newTab().setText("Complaint List"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final PagerAdapter adapter =
new com.six30labs.cms.adapters.PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
Second fragment which contains my listview
public class ComplaintListFragment extends Fragment {
private ListView complaintListView;
EditText _inputSearch;
ComplaintAdapter compadapter;
private static Parcelable mListViewScrollPos = null;
private RequestQueue mQueue;
ProgressBar progressBar;
String URL;
private View v;
String TAG="Second Fragment";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_complaint_list, container, false);
complaintListView = (ListView) v.findViewById(R.id.complaintListView);
_inputSearch = (EditText) v.findViewById(R.id.inputSearchforComplaintListFragment);
progressBar = (ProgressBar) v.findViewById(R.id.complaintListProgressBar);
fetchComplaintData();
_inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try {
compadapter.getFilter().filter(s.toString());
compadapter.notifyDataSetChanged();
}catch (NullPointerException e){
e.printStackTrace();
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
if (mListViewScrollPos != null) {
complaintListView.onRestoreInstanceState(mListViewScrollPos);
}
return v;
}
public void fetchComplaintData() {
progressBar.setVisibility(View.VISIBLE);
URL = URLMap.getComplaintUrl("complaint_url");
URL = URL.replace("{id}", LoggedInUserStore.getLoggedInCompanyId(getContext()));
StringRequest request = new StringRequest(Request.Method.GET,URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
getCompliantList(response);
progressBar.setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
request.setRetryPolicy(new VolleyRetryPolicy().getRetryPolicy());
RequestQueue queue=((VolleyRequestQueue)getActivity().getApplication()).getRequestQueue();
queue.add(request);
/* RequestQueue requestQueue
= Volley.newRequestQueue(getContext());
requestQueue.add(request);*/
}
public void getCompliantList(String response) {
try {
List complaint = new ArrayList<>();
JSONArray jArray = new JSONArray(response);
for (int i = 0; i < jArray.length(); i++) {
// complaint.add(Complaint.fromJson(jArray.getJSONObject(i)));
complaint.add(0,Complaint.fromJson(jArray.getJSONObject(i))); //To push the data to the top of the listview.
}
compadapter = new ComplaintAdapter(getContext(), complaint);
complaintListView.setAdapter(compadapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
//Method that will save the position the user when they scroll
//return it when the user comes back to the listView instead of it refreshing the data.
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mListViewScrollPos = complaintListView.onSaveInstanceState();
}
public void onPause() {
super.onPause();
}
public void onResume() {
super.onResume();
fetchComplaintData();
}
BroadcastReceiver For class Where your Listview is
private BroadcastReceiver updateProfileBroadcast = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Fire your event
}
};
Register Broadcast in onResume()
registerReceiver(updateProfileBroadcast, new IntentFilter("KEY"));
Now fire Broadcast From Fragment
Intent intent = new Intent("KEY");
getActivity().sendBroadcast(intent);
As an alternative to SID's answer you may use EventBus. It works by event-driven architecture and able to transfer information between components really easy and fast.
That's how you use it:
1) add to project in app gradle: compile 'org.greenrobot:eventbus:3.0.0'
2) Register EventBus in fragment's onCreate() where you need to update ListView: eventBus.register(this);. And don't forget to unregister it on onDestryView(): eventBus.unregister(this);
3) Add the method to your ListView fragment which will handle event with list update:
#SupressWarning("unused")
#Subscribe
public void onEvent(List<YourListViewData> event) {/* update `ListView` */};
4) Fire that event from activity\fragment when you need to update ListView:
EventBus bus = EventBus.getInstance();
eventBus.post(List<YourListViewData> yourData);