Android tcp/ip read and write buffer out of main code - android

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.

Related

android viewpager2 page buton controller

if the page is loaded, the button is active, if not, how can I do passive control?
What I want to do is, if the Viewpager Page is loaded, the button is active, if not, the Button is Passive. But I couldn't do any kind.
Is there anyone who can help?
If viewpager2 is installed Button enabled, if viewpager2 is not installed button false;
List<Movie> movieList = new ArrayList<>();
private ImageButton btn_down, btn_fav;
private Button btn_setter;
private DatabaseReference movies;
private IFirebaseLoadDone iFirebaseLoadDone;
public CartoonFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_cartoon, container, false);
movies = FirebaseDatabase.getInstance().getReference("Sports");
movies.keepSynced(true);
iFirebaseLoadDone = this;
loadMovie();
viewPager2 = view.findViewById(R.id.viewPager2_);
btn_down = view.findViewById(R.id.btn_down);
btn_setter = view.findViewById(R.id.btn_setter);
btn_fav = view.findViewById(R.id.btn_fav);
btn_down.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SaveToGallery();
}
});
btn_setter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
btn_fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return view;
}
private void loadMovie() {
movies.addValueEventListener(this);
}
#Override
public void onFirebaseLoadSuccess(List<Movie> movieList) {
viewPagerAdapter = new ViewPagerAdapter(getContext(), movieList, viewPager2);
viewPager2.setAdapter(viewPagerAdapter);
}
#Override
public void onFirebasLoadFailed(String message) {
}
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot moviesSnapShot : dataSnapshot.getChildren())
movieList.add(moviesSnapShot.getValue(Movie.class));
Collections.reverse(movieList);
iFirebaseLoadDone.onFirebaseLoadSuccess(movieList);
viewPagerAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
iFirebaseLoadDone.onFirebasLoadFailed(databaseError.getMessage());
}
#Override
public void onDestroy() {
movies.removeEventListener(this);
super.onDestroy();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onStop() {
movies.removeEventListener(this);
super.onStop();
}
}
Replace your methods with mine.
private void loadMovie() {
movies.addValueEventListener(this);
btn_down.setEnabled(false);
btn_fav.setEnabled(false);
btn_setter.setEnabled(false);
}
Firebase methods
#Override
public void onFirebaseLoadSuccess(List<Movie> movieList) {
viewPagerAdapter = new ViewPagerAdapter(getContext(), movieList, viewPager2);
viewPager2.setAdapter(viewPagerAdapter);
if(movieList!=null && !movieList.isEmpty()){
btn_down.setEnabled(true);
btn_fav.setEnabled(true);
btn_setter.setEnabled(true);
}
}
#Override
public void onFirebasLoadFailed(String message) {
btn_down.setEnabled(false);
btn_fav.setEnabled(false);
btn_setter.setEnabled(false);
}
There was an error loading
private void loadMovie() {
movies.addValueEventListener(this);
btn_down.setEnabled(false);
btn_fav.setEnabled(false);
btn_setter.setEnabled(false);
}
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setEnabled(boolean)' on a null object reference
at com.example.duvarlar.Fragment.CartoonFragment.loadMovie(CartoonFragment.java:386)
at com.example.duvarlar.Fragment.CartoonFragment.onCreateView(CartoonFragment.java:90)

how to write a variable from a singleton in firebase

There is a program where I can change a variable using a singleton. Created 2 activites, where users can change this variable. How to write the variable that is being changed to the Firebase database. I tried to use the addValueEventListener (new ValueEventListener () method.
Where do I use the firebase methods? In the main class or in singleton? And how to write a variable?
main activity
public class MainActivity extends AppCompatActivity {
private BubbleWrap bubbleWrap;
private TextView txtintent;
final int REQUEST_CODE_661_1 = 1;
private int bbbbb;
private TextView txt;
private String bubul;
FirebaseDatabase database=FirebaseDatabase.getInstance();
final DatabaseReference AllFacebase =database.getReference("всего").child("йй");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt=findViewById(R.id.textView);
bubbleWrap=BubbleWrap.getInstance();
setupAddMoreButton();
setupPopActivityButton();
setupCocActivityButton();
txtintent=(TextView)findViewById(R.id.txtintent);
AllFacebase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
bubul=String.valueOf(dataSnapshot.getValue());
txtintent.setText(bubul);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
protected void onResume() {
super.onResume();
updateUI();
}
private void setupAddMoreButton(){
Button btn=findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bubbleWrap.addMoreBubbles();
updateUI();
}
});
}
private void setupPopActivityButton(){
Button btn=findViewById(R.id.button2);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private void setupCocActivityButton(){
Button btn=findViewById(R.id.buttoncoc);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
private void updateUI(){
txtintent.setText(String.format(Locale.getDefault(),"%d",
bubbleWrap.getNumBubbles()));
}
}
second activity
activity, where I change the variable, I want to write to Firebase
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pop);
bubbleWrap=BubbleWrap.getInstance();
final TextView txt=findViewById(R.id.textView2);
setupPopButton();
updateUI();
Intent intent=new Intent();
intent.putExtra("bubles", bubbleWrap.getNumBubbles());
}
private void setupPopButton(){
Button btn=findViewById(R.id.cocbtb);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bubbleWrap.popBubble();
updateUI();
}
});
}
private void updateUI(){
TextView txt=findViewById(R.id.textView2);
txt.setText(String.format(Locale.getDefault(),
"Bubbles left: %d",
bubbleWrap.getNumBubbles()));
}
}
Singleton
public class BubbleWrap {
private static final int ADD_MORE_BUBBLES = 10;
private int numBubbles;
private static BubbleWrap instance;
private BubbleWrap(){
}
public static BubbleWrap getInstance(){
if(instance==null){
instance=new BubbleWrap();
}
return instance;
}
public int getNumBubbles() {
return numBubbles;
}
public void addMoreBubbles(){
numBubbles+=ADD_MORE_BUBBLES;
}
public void popBubble() {
numBubbles--;
}
public void saveintent(){
}
}

Issue with coding the communication between a fragment and an async task

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;
}

How to refresh RecyclerView from button on DialogFragment

I have an application with a RecyclerView and a DialogFragment, in the Dialog I add data to the database and display it in the RecyclerView. I tried to refresh the RecyclerView when I clicked in to add.
This is the Fragment
public class addAction extends DialogFragment implements View.OnClickListener {
EditText addTitle, addDesc;
Button add, clear,close;
Context context;
private DatabaseHelpher db;
String Title,Des;
public addAction() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.addaction, container, false);
addTitle = (EditText) rootView.findViewById(R.id.todotitle);
addDesc = (EditText) rootView.findViewById(R.id.tododescription);
add = (Button) rootView.findViewById(R.id.addbutton);
add.setOnClickListener(this);
close = (Button) rootView.findViewById(R.id.Close);
close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dismiss();
}
});
clear = (Button) rootView.findViewById(R.id.clear);
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addTitle.setText("");
addDesc.setText("");
}
});
return rootView;
}
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getDialog().setTitle("Add Action");
db = new DatabaseHelpher(getContext());
}
private void insert() {
Title = addTitle.getText().toString();
Des= addDesc.getText().toString();
db.insertIntoDB(Title, Des);
}
#Override
public void onClick(View v) {
if (addTitle.getText().toString().trim().equals("")) {
addTitle.setError(" Title is required!");
} else if (addDesc.getText().toString().trim().equals("")) {
addDesc.setError(" Postion is required!");
}
insert();
}
}
and this is the MainActivity
public class MainActivity extends AppCompatActivity {
List<ToDoModule> dbList;
RecyclerView mRecyclerView;
DatabaseHelpher helpher;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().hide();
helpher = new DatabaseHelpher(this);
dbList= new ArrayList<ToDoModule>();
dbList = helpher.getDataFromDB();
mRecyclerView = (RecyclerView)findViewById(R.id.AppRecyclerView);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new RecyclerAdapter(this,dbList);
mAdapter.notifyDataSetChanged();
mRecyclerView.setAdapter(mAdapter);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setImageResource(R.drawable.ic_action_name);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager fm = getSupportFragmentManager();
addAction add = new addAction();
add.show(fm, "fragment_edit_name");
}
});}
#Override
protected void onResume() {
super.onResume();
dbList = helpher.getDataFromDB();
mAdapter.notifyDataSetChanged();
}
}
Call mAdapter.notifyDataSetChanged(); in your Activity's onResume() method.
First Solution
cast activity and call your method like this:
in your activity add this method
public void myMethod(){
runOnUiThread(new Runnable() {
#Override
public void run() {
//your code here
}
});
}
in your DialogFragment call the activity method after you cast it.
((YourActivity)getActivity()).myMethod();
Second Solution
add eventbus to your gradle
compile 'org.greenrobot:eventbus:3.0.0'
make a class that you want to pass to activity
public class MessageEvent {
public final String message;
public MessageEvent(String message) {
this.message = message;
}
}
listen to events in your activity
// This method will be called when a MessageEvent is posted (in the UI thread for Toast)
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {
Toast.makeText(getActivity(), event.message, Toast.LENGTH_SHORT).show();
}
register EventBus in your Activity
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
EventBus.getDefault().unregister(this);
super.onStop();
}
finally send in Event from Dialog to your Activity
EventBus.getDefault().post(new MessageEvent("Hello everyone!"));
don't forgot adding this to proguard file
-keepattributes *Annotation*
-keepclassmembers class ** {
#org.greenrobot.eventbus.Subscribe <methods>;
}
-keep enum org.greenrobot.eventbus.ThreadMode { *; }

Replace fragment in ActionBar Tabs that have swipe view

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 :)

Categories

Resources