Reputation: 12010
I have an Android application, which has a lot of articles. If you open an article a new activity is created. Now there is a part in the activity which is always the same, but it send a request to the server to get the data. I was thinking to make a fragment which will load the data only once (probably in MainActivity) and show it to all activities. Is this possible and how do I do it?
I also tried creating a fragment, but it still loads the data every time a new activity is created. Here is the XML code.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="@+id/textView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#000000" />
<!-- There is more layout, but I don't think it is needed for now -->
</RelativeLayout>
And Java
private class getMessage extends AsyncTask<Void , Void, Void>{
@Override
protected Void doInBackground(Void... params) {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httppost = new HttpGet("http:///www.example.com");
HttpResponse response;
try {
response = httpclient.execute(httppost);
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
InputStream is = buf.getContent();
BufferedReader r = new BufferedReader(new InputStreamReader(is));
total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line + "\n");
}
}
catch (ClientProtocolException e) {}
catch (IOException e) {}
return null;
}
@Override
protected void onPostExecute(Void args){
try{
textView.setText(total.toString());
}
catch(Exception e){}
}
}
And the code to add the fragment
FragmentManager fragMan = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragTransaction = fragMan.beginTransaction();
Fragment fragment = new Fragment();
fragTransaction.add(R.id.fragment_replace, fragment);
fragTransaction.commit();
Upvotes: 2
Views: 99
Reputation: 4936
You are trying to cache data using Fragment, but as you can see at documentation:
A Fragment represents a behavior or a portion of user interface in an Activity
source: Fragments
Fragment should be used to avoid "copy-paste" in user interface code.
But you are trying to cache the data from network. This is not mission of Fragment. This is not Tier when you should process data. At Fragment you should only load already cached data.
I can recomend you choose one of next solutions:
1). Use SQLite database to cache data.
If you want to cache data in SQLite, I recomend you use pattern, which Virgil Dobjanschi described at Google I/O conference in 2010(link to video here)
Also, I think this example may be helpful for implementing this pattern.
2). Use some network libraries, which can help you to cache data
Robospice - is a modular android library that makes writing asynchronous long running tasks easy. It is specialized in network requests, supports caching and offers REST requests out-of-the box using extension modules.
link: Robospice
example project: Robospice+Retrofit
Short description how to cache:
getSpiceManager().execute(githubRequest, "github", DurationInMillis.ONE_MINUTE, new ListContributorRequestListener());
"github"
- is a key. DurationInMillis.ONE_MINUTE
- time while cached data will be actual. This means, that if you are executed this request first time, data will be loaded from network. If you are executed this request second time during 1 minute, then data will be loaded from local cache.
Possible values of DurationInMillis
from docs:
**Field Summary**
static long ALWAYS
Deprecated.
static long ALWAYS_EXPIRED
Data in cache will never be returned, a network call will always be performed.
static long ALWAYS_RETURNED
Data in cache will always be returned.
static long NEVER
Deprecated.
static long ONE_DAY
static long ONE_HOUR
static long ONE_MINUTE
static long ONE_SECOND
static long ONE_WEEK
OkHttp - from docs:
OkHttp is an HTTP client that’s efficient by default:
link: OkHttp
example project: samples
Short description how to cache:
// Create an HTTP client that uses a cache on the file system. Android applications should use
// their Context to get a cache directory.
OkHttpClient okHttpClient = new OkHttpClient();
File cacheDir = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
HttpResponseCache cache = new HttpResponseCache(cacheDir, 1024);
okHttpClient.setResponseCache(cache);
Full example here
Upvotes: 0
Reputation: 39836
Fragments belong to only one activity. After you commit()
the transaction, that fragment "belongs" to that activity.
If you want a higher level sharing or network related data, I suggest you to implement it in a Bound Service
and have activities or fragments to get this data directly from the Service
Upvotes: 1
Reputation: 1170
If you have only one activity in your application, it is possible. But you cant show the loaded fragment in many activities.
Only after adding the fragment to the container, you can attach and detach a fragment.
Upvotes: 0