Issue
I'm creating an Android App using Android Studio. I'm using Navigation Drawer template. I want to show data from web using http and async task in home fragment. I copy paste code of class from the internet that fetch data from web.
This is the class :
class FetchThingspeakTask extends AsyncTask<Void, Void, String> {
protected void onPreExecute() {
Toast.makeText(getApplicationContext(), "Fetching Data from Server.Please Wait...", Toast.LENGTH_SHORT).show();
}
protected String doInBackground(Void... urls) {
try {
URL url = new URL("https://api.thingspeak.com/channels.json?api_key=I9CEDD46LZX2HZTC");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if(response == null) {
Toast.makeText(MainActivity.this, "There was an error", Toast.LENGTH_SHORT).show();
return;
}
// I want to get this response and use it in any fragment
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
}
}
I put that class in MainActivity.java and execute that in main activity. I execute this class every one minute using timer and handler.
I actually get the response but the response is not usable in fragment. I want to take data from the class that call API and giving response in all fragments.
this is full main activity code:
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
setRepeatingAsyncTask();
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow,
R.id.nav_tools, R.id.nav_share, R.id.nav_send)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration)
|| super.onSupportNavigateUp();
}
class FetchThingspeakTask extends AsyncTask<Void, Void, String> {
protected void onPreExecute() {
Toast.makeText(getApplicationContext(), "Fetching Data from Server.Please Wait...", Toast.LENGTH_SHORT).show();
}
protected String doInBackground(Void... urls) {
try {
URL url = new URL("https://api.thingspeak.com/channels.json?api_key=I9CEDD46LZX2HZTC");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if(response == null) {
Toast.makeText(MainActivity.this, "There was an error", Toast.LENGTH_SHORT).show();
return;
}
// I want to get this response and use it in any fragment
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG).show();
}
}
private void setRepeatingAsyncTask() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
new FetchThingspeakTask().execute();
}
catch(Exception e){
Log.e("ERROR", e.getMessage(), e);
}
}
});
}
};
timer.schedule(task, 0, 60*1000); // interval of one minute
}
}
Is there any suggest how to do that ?
Update:
I want this response will dynamically update in fragment
Solution
Declare global variable for fragment
Fragment fragmentRef = new MyFragment() // your fragment name
Now Inside onPostExecute()
For the very first API call, make your fragment transaction means inflate fragment from activity
getFragmentManager().beginTransaction().replace(R.id.container, fragmentRef, "TAG).commit()
make setData() method in fragment and call using fragmentRef
fragmentRe.setData(response) //pass your data
Now for next/subsequent API calls, check and get your fragment from fragmentManager by using findFragmentByTag() , once you get fragment reference, then call setData() Method
if( fragmentRef !=null){
fragmentRef.setData(response)
}
Answered By - Kishan Maurya
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.