Android: Make LazyLoading ListView from GSON available without internet - android

I've just implemented GSON to Fedor's LazyLoading ListView. That means the app saves the downloaded images and texts from the web to the external storage though an ImageLoader class.
and I wonder why how to make this listview accessible without an internet connection.
Here I give you a snippet of my ListView Class:
public class ProjectsList extends Activity {
ListView lstTest;
ProjectAdapter arrayAdapter;
ArrayList<Project> prjcts=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.projects_list);
//Initialize ListView
lstTest= (ListView)findViewById(R.id.lstText);
prjcts = new ArrayList<Project>();
arrayAdapter = new ProjectAdapter(ProjectsList.this, R.layout.listitems,prjcts,ProjectsList.this);
lstTest.setAdapter(arrayAdapter);
if (isOnline())
{
WebService webService = new WebService("http://liebenwald.spendino.net/admanager/dev/android/projects.json");
Map<String, String> params = new HashMap<String, String>();
params.put("var", "");
String response = webService.webGet("", params);
try
{
Type collectionType = new TypeToken<ArrayList<Project>>(){}.getType();
List<Project> lst= new Gson().fromJson(response, collectionType);
for(Project l : lst)
{
prjcts.add(l);
ConstantData.projectsList.add(l);
}
arrayAdapter.notifyDataSetChanged();
}
catch(Exception e)
{
Log.d("Error: ", e.getMessage());
}
}
lstTest.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent care = new Intent(ProjectsList.this, ProjectDetail.class);
care.putExtra("spendino.de.ProjectDetail.position",position);
startActivity(care);
}
});
}
#Override
public void onDestroy()
{
yAdapter.imageLoader.stopThread();
lstTest.setAdapter(null);
super.onDestroy();
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
return true;
} else {
}
});
return false;
}
}
}
Please advise if more of my codes are required.
Thanks

Look, you need to have the data in your application so that you can call them when no internet connection is available...
When you are getting the data save it somewhere in your application.Then pass the data in your Adapter..
The images will not be downloaded again...
In Fedor's lazylist the url of the images are static but here they are coming dynamically.
Hope this will help you.

Related

Json Data reload again on configuration changes in background tasks

I have made an app Earthquake Report app. in that I am fetching earthquake data through an API and showing it in recycler view.
This process runs on the background thread by using the Executor service method and runnable.
But when I run my app and when I rotated my phone the background process is re-executed and reloads data .
How to prevent it? I am using Java for making app.
RecyclerView recyclerView;
LinearLayout nointernetLinearLayout;
ArrayList<EarthquakeModel> earthquake;
private ImageView mEmptyView;
private Button mNoInternetButton;
boolean isConnected;
private static final String url = "https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2021-09-10&endtime=2021-09-11";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_view);
nointernetLinearLayout = findViewById(R.id.no_internet);
mEmptyView = findViewById(R.id.empty_view);
earthquake = new ArrayList<>();
ExecutorService service = Executors.newSingleThreadExecutor();
service.execute(new Runnable() {
#Override
public void run() {
QueryUtils queryUtils = new QueryUtils();
String json = queryUtils.call(url);
try {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
if (isConnected){
Log.i("This is background task","it is restarted if showing again");
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("features");
for (int i=0; i<jsonArray.length(); i++){
JSONObject c = jsonArray.getJSONObject(i);
JSONObject properties = c.getJSONObject("properties");
double magnitude = properties.getDouble("mag");
String location = properties.getString("place");
long time = properties.getLong("time");
String url = properties.getString("url");
EarthquakeModel earthquakeModel = new EarthquakeModel(location, magnitude,time,url);
earthquake.add(earthquakeModel);
}
}
}catch (JSONException e){
Log.e("Error","is"+e.getMessage());
}
runOnUiThread(new Runnable() {
#Override
public void run() {
View loadingIndicator = findViewById(R.id.loading_indicator);
loadingIndicator.setVisibility(View.GONE);
if (isConnected&&!earthquake.isEmpty()){
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
EarthquakeAdapter earthquakeAdapter = new EarthquakeAdapter(earthquake,MainActivity.this);
recyclerView.setAdapter(earthquakeAdapter);
}if(isConnected&&earthquake.isEmpty()){
recyclerView.setVisibility(View.GONE);
mEmptyView.setVisibility(View.VISIBLE);
}
if (!isConnected){
recyclerView.setVisibility(View.GONE);
nointernetLinearLayout.setVisibility(View.VISIBLE);
}
});
}
});
}
Run the service in your viewModel, since the viewmodel survives the configuration change.
The update the UI with LiveData.
public ExampleViewModel extends ViewModel {
private MutableLiveData<ArrayList<EarthquakeModel>> earthquake;
public ExampleViewModel() {
ExecutorService service = Executors.newSingleThreadExecutor();
service.execute(new Runnable() {
//get data
earthquake.post(someData)
}
}
public LiveData<ArrayList<EarthquakeModel>> getEarthQuake() {
return earthquake;
}
}
Then in your Activity observe the LiveData
public class ExampleActivity extends Activity {
private ExampleViewModel exampleViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
exampleViewModel = new ViewModelProvider(this).get(ExampleViewModel.class);
exampleViewModel.getEarthQuake().observe(getViewLifecycleOwner(), array -> {
//do somthing with array
}
}
}

Download corresponding file too RecyclerView row

I need help with a programming part in Android Studio.
I have a RecyclerView corresponding to a json array from my database. In this array are some informations given to fill the RecyclerView. Every json object has an URL for a corresponding file on a webserver too.
At this part I need your help. I need to fetch the URL from every json object and download the corresponding file to the device and set it to the RecyclerView row.
The URL in the json has the name: download_url (not in my code at the moment but in the json array.
The download state should be shown in the status bar with a progress view (I need to add some informations like the name to the notification). When the user clicks the row the PDF file should be shown in a PFD viewer.
The next thing is to delete these files from device. They should be deleted automatically if the user refreshs the RecyclerView and the given json don't has the file anymore.
The URL has the filename at the the end corresponding to the file on the server.
Thanks for your idea's. I'm a beginner and try to give my best to learn a lot from tutorials but this question is very hard and specific for me.
This is my Adapter:
public class PlansAdapter extends RecyclerView.Adapter<PlansAdapter.MyPlanHolder> {
private List<Plans> planList;
private final Context customContext;
public class MyPlanHolder extends RecyclerView.ViewHolder {
public TextView planTitle, planType, planDate;
public MyPlanHolder(View view) {
super(view);
planTitle = (TextView) view.findViewById(R.id.planTitle);
planType = (TextView) view.findViewById(R.id.planTyp);
planDate = (TextView) view.findViewById(R.id.planDate);
}
}
public PlansAdapter(List<Plans> planList, Context customContext) {
this.planList = planList;
this.customContext = customContext;
}
#Override
public MyPlanHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.plans_list_row, parent, false);
return new MyPlanHolder(itemView);
}
#Override
public void onBindViewHolder(MyPlanHolder holder, int position) {
final Plans plan = planList.get(position);
// Format timestamp to date
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
String resultDate = null;
try {
date = fmt.parse(plan.getPlanDate());
SimpleDateFormat fmtOut = new SimpleDateFormat("dd.MM.yyyy");
resultDate = fmtOut.format(date);
} catch (Exception e) {
e.printStackTrace();
}
holder.planTitle.setText(plan.getPlanTitle());
holder.planType.setText(plan.getEatingPlanType() + " " + plan.getTrainingPlanType());
holder.planDate.setText("resultDate);
}
#Override
public int getItemCount() {
return planList.size();
}
}
This is my Request.class where I get the json Object:
public class PlansRequest extends StringRequest {
public static final String PLANS_REQUEST_URL = "http://hiddenwebserver.de/de/json";
private Map<String, String> params;
public PlansRequest(String loginEmail, Response.Listener<String> listener) {
super(Request.Method.POST, PLANS_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("loginEmail", loginEmail);
}
#Override
public Map<String, String> getParams() {
return params;
}
}
This is where I set the RecyclerView on my Fragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_training, container, false);
// Get Refresh Layout
swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.training_swiperefresh);
// Connectivity manager for network check
final ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
// Change color for the refresh layout
swipeRefreshLayout.setColorSchemeColors(Color.rgb(99, 195, 195));
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
// Check if network connection exists
if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
// Get plans data from web
getPlansData();
} else {
// Error message if internet connection is not available
Toast.makeText(getActivity(), getString(R.string.noInternetConnection), Toast.LENGTH_LONG).show();
}
}
});
trainingRecyclerView = (RecyclerView) view.findViewById(R.id.training_recycler_view);
pAdapter = new PlansAdapter(planList, getContext());
RecyclerView.LayoutManager pLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
trainingRecyclerView.setLayoutManager(pLayoutManager);
trainingRecyclerView.setItemAnimator(new DefaultItemAnimator());
trainingRecyclerView.setAdapter(pAdapter);
preparePlansData();
return view;
}
This is where I prepare the data from the json array:
private void preparePlansData() {
// Connectivity manager for network check
final ConnectivityManager connectivityManager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
// Check if network connection exists
if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
// Get shared preferences
SharedPreferences plansPreferenceData = getActivity().getSharedPreferences("plansData", MODE_PRIVATE);
if (plansPreferenceData.contains("plansPreferenceData")) {
String plansData = plansPreferenceData.getString("plansPreferenceData", "").replace("\"success\":true,", "");
// Remove success string from jsonResponse
//plansData.replace("success\":true,", "");
Log.d("plansData", "Result:" + plansData);
Gson gson = new Gson();
Type type = new TypeToken<Map<String, Plans>>(){}.getType();
Map<String, Plans> myPlansMap = gson.fromJson(plansData, type);
planList.addAll(myPlansMap.values());
// Notify data changes
pAdapter.notifyDataSetChanged();
// Now we call setRefreshing(false) to signal refresh has finished
swipeRefreshLayout.setRefreshing(false);
} else {
getPlansData();
}
} else {
// Error message if internet connection is not available
Toast.makeText(getActivity(), getString(R.string.noInternetConnectionOnStart), Toast.LENGTH_LONG).show();
}
}

Android twitter async task crashes in landscape

Been on the same problem for too many hours, so I figured why not ask the stackoverflow community.
I have implemented twitter it works fine if the orientation is in portrait. If I would turn the phone in landscape during the async call it crashes. I have seen a few examples of this issue and have tried a few of them. locking the screen is not a solution.
I'll try to post a snippet of the code. maybe someone can give me a tip. Thanks
Logcat Error
12-03 16:43:01.650 18351-18351/com.example.admin.football E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.admin.football.fragments.TwitterFragment.onTaskFinished(TwitterFragment.java:94)
at com.example.admin.football.fragments.TwitterFragment$DownloadTwitterTask.onPostExecute(TwitterFragment.java:193)
at com.example.admin.football.fragments.TwitterFragment$DownloadTwitterTask.onPostExecute(TwitterFragment.java:171)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4797)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
at dalvik.system.NativeStart.main(Native Method)
Java code:
public TwitterFragment()
{
}
#Override
public void onTaskStarted() {
isTaskRunning = true;
load(listView);
}
// converts a string of JSON data into a Twitter object
private Twitter jsonToTwitter(String result) {
Twitter twits = null;
if (result != null && result.length() > 0) {
try {
Gson gson = new Gson();
twits = gson.fromJson(result, Twitter.class);
} catch (IllegalStateException ex) {
// just eat the exception
}
}
return twits;
}
#Override
public void onTaskFinished(String result) {
if (spinner != null) {
final Twitter twits = jsonToTwitter(result);
if(twits!=null) {
// lets write the results to the console as well
for (Tweet tweet : twits) {
Log.i(LOG_TAG, tweet.getText());
}
cardArrayAdapter = new CardArrayAdapter(getActivity().getApplicationContext(), R.layout.list_item_card);
for (int i = 0; i < twits.size(); i++) {
String dt = twits.get(i).getDateCreated();
Card card = new Card(twits.get(i).getUser().getProfileImageUrl(), twits.get(i).getUser().getScreenName(), twits.get(i).toString(), dt.substring(0, 10));
cardArrayAdapter.add(card);
}
listView.setAdapter(cardArrayAdapter);
/*cardArrayAdapter.getFilter().filter(Hashtag, new Filter.FilterListener() {
#Override
public void onFilterComplete(int count) {
listView.setAdapter(cardArrayAdapter);
}
});*/
spinner.setVisibility(View.GONE);
}
spinner.setVisibility(View.GONE);
}
isTaskRunning = false;
}
#Override
public void onDetach() {
// All dialogs should be closed before leaving the activity in order to avoid
// the: Activity has leaked window com.android.internal.policy... exception
if (spinner != null) {
spinner.setVisibility(View.GONE);
}
super.onDetach();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// If we are returning here from a screen orientation
// and the AsyncTask is still working, re-create and display the
// progress dialog.
if (isTaskRunning) {
load(listView);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_twitter, container, false);
listView = (ListView) rootView.findViewById(R.id.card_listView);
spinner = (ProgressBar)rootView.findViewById(R.id.progressBar1);
spinner.setVisibility(View.GONE);
listView.addHeaderView(new View(getActivity()));
listView.addFooterView(new View(getActivity()));
// call method to download tweets
downloadTweets();
return rootView;
}
public void load(View view){
spinner.setVisibility(View.VISIBLE);
}
// download twitter timeline after first checking to see if there is a network connection
public void downloadTweets() {
ConnectivityManager connMgr = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
load(listView);
new DownloadTwitterTask(this).execute(ScreenName);
} else {
Log.v(LOG_TAG, "No network connection available.");
}
}
// Uses an AsyncTask to download a Twitter user's timeline
//TODO cancel this when view is changed!
public class DownloadTwitterTask extends AsyncTask<String, Void, String> {
private final TaskListener listener;
final static String CONSUMER_KEY = "";
final static String CONSUMER_SECRET = "";
final static String TwitterTokenURL = "https://api.twitter.com/oauth2/token";
final static String TwitterStreamURL = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=";
public DownloadTwitterTask(TaskListener listener) {
this.listener = listener;
}
#Override
protected String doInBackground(String... screenNames) {
String result = null;
if (screenNames.length > 0) {
result = getTwitterStream(screenNames[0]);
}
return result;
}
// onPostExecute convert the JSON results into a Twitter object (which is an Array list of tweets
#Override
protected void onPostExecute(String result) {
listener.onTaskFinished(result);
}
// convert a JSON authentication object into an Authenticated object
private Authenticated jsonToAuthenticated(String rawAuthorization) {
Authenticated auth = null;
if (rawAuthorization != null && rawAuthorization.length() > 0) {
try {
Gson gson = new Gson();
auth = gson.fromJson(rawAuthorization, Authenticated.class);
} catch (IllegalStateException ex) {
// just eat the exception
}
}
return auth;
}
Well even if somebody gave a solution i want to try to give a better one.
Using configChanges won't let your application to reload resources when the screen is rotated, this means that if you are using different layouts or other resources for landscapes and portaits they will be totally unuseful.
You should call your AsyncTask from a fragment and use the setRetainInstance(true) method, here you will find a good explanation on how to do it.
Add this line in your Activity entry in Manifest:
android:configChanges="layoutDirection|keyboardHidden|orientation|screenSize|screenLayout"

Managing the background thread within Android application

I currently have this class below which parses json urls and loads images and texts into a listview with the help of the Lazy Adapter Class and background thread.
Each list item consists of an image view and 2 text views.
I want to create pop up boxes (alert dialog) for each of the generated list items. The alert dialog will have options which will call other applications.
My question :
Would it be wise to code this alert dialog functionality in this class? I'm worried that there is a lot of stuff currently being done in the background and it might affect the app's functionality.
If not could anyone suggest another way to do it. thanks.
Json Activity Class :
public class JsonActivity extends SherlockActivity{
private ProgressDialog progressDialog;
// JSON Node names
static final String TAG_NAME = "name";
static final String TAG_IMAGEURL = "imageurl";
ListView list;
LazyAdapter adapter;
String chartUrl;
String[] urlNames = new String[] {
"urls..."
};
// chartItemList is the array list that holds the chart items
ArrayList<HashMap<String, String>> chartItemList = new ArrayList<HashMap<String,
String>>();
//Holds imageurls
ArrayList<String> imageurls = new ArrayList<String>();
JsonParser Parser = new JsonParser();
// JSONArray
JSONArray chartItems = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chart);
//Get the bundle
Bundle bundle = getIntent().getExtras();
//Extract the data from the bundle
int chartIndex = bundle.getInt("chartIndex");
String chartUrl = urlNames[chartIndex];
setTitle(bundle.getString("chartname"));
//url from where the JSON has to be retrieved
String url = chartUrl;
//Check if the user has a connection
ConnectivityManager cm = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null) {
if (!info.isConnected()) {
Toast.makeText(this, "Please check your connection and try again.",
Toast.LENGTH_SHORT).show();
}
//if positive, fetch the articles in background
else new getChartItems().execute(chartUrl);
}
//else show toast
else {
Toast.makeText(this, "Please check your connection and try again.",
Toast.LENGTH_SHORT).show();
}
}
class getChartItems extends AsyncTask<String, String, String> {
// Shows a progress dialog while setting up the background task
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(JsonActivity.this);
progressDialog.setMessage("Loading chart...");
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.show();
}
//Gets the json data for chart items data and presents it in a list view
#Override
protected String doInBackground(String... args) {
String json = Parser.getJSONFromUrl(args[0]);
String imageurl;
String rank;
String name;
String url;
try{
chartItems = new JSONArray(json);
JSONObject json_data=null;
for(int i=0;i<chartItems.length();i++){
json_data = chartItems.getJSONObject(i);
//Retrieves the value of the name from the json object
name=json_data.getString("name");
//Retrieves the image url for that object and adds it to an arraylist
imageurl=json_data.getString("imageurl");
//imageurls.add(imageurl);
HashMap<String, String> hashMap = new HashMap<String, String>();
// adding each child node to HashMap key => value
//hashMap.put(TAG_RANK, rank);
hashMap.put(TAG_NAME, name);
hashMap.put(TAG_IMAGEURL, imageurl);
// adding HashMap to ArrayList
chartItemList.add(hashMap);
}
;
}
catch (JSONException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
public void run() {
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter = new LazyAdapter(JsonActivity.this, chartItemList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
});
return null;
}
//Removes the progress dialog when the data has been fetched
protected void onPostExecute(String args) {
progressDialog.dismiss();
}
}
}
My answer for this is Yes, it is wise enough to implement one more level network communication as far as your use case justifies it.
This depends on communication channel (EDGE/ 3G/ 4G/ WiFi) and use case of the application. Technically it is pretty much possible as far as you are doing this in background. It also depends on the size of the list which you are loading. Best way to check this is by implementing plug-able code and try it out.

Android: Save JSON data into SharedPreferences

I have this ListView which fetches its data (image+text) from JSON on the web.
Now I have a task to make the ListView is accessible without internet connection. My idea is by saving the JSON data from the web when the app is run for the first time with internet, and when it can't find internet connection it will get the data from the persistent Storage.
Can anybody help me with this? I'm still a beginner can't find the example of SharedPreferences with JSON.
Thanks a lot
public class ProjectsList extends Activity {
/** Called when the activity is first created. */
//ListView that will hold our items references back to main.xml
ListView lstTest;
//Array Adapter that will hold our ArrayList and display the items on the ListView
ProjectAdapter arrayAdapter;
//List that will host our items and allow us to modify that array adapter
ArrayList<Project> prjcts=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.projects_list);
//Initialize ListView
lstTest= (ListView)findViewById(R.id.lstText);
//Initialize our ArrayList
prjcts = new ArrayList<Project>();
//Initialize our array adapter notice how it references the listitems.xml layout
arrayAdapter = new ProjectAdapter(ProjectsList.this, R.layout.listitems,prjcts,ProjectsList.this);
//Set the above adapter as the adapter of choice for our list
//lstTest.setAdapter(arrayAdapter);
lstTest.setAdapter(arrayAdapter);
if (isOnline())
{
//Instantiate the Web Service Class with he URL of the web service not that you must pass
WebService webService = new WebService("http://liebenwald.spendino.net/admanager/dev/android/projects.json");
//Pass the parameters if needed , if not then pass dummy one as follows
Map<String, String> params = new HashMap<String, String>();
params.put("var", "");
//Get JSON response from server the "" are where the method name would normally go if needed example
// webService.webGet("getMoreAllerts", params);
String response = webService.webGet("", params);
try
{
//Parse Response into our object
Type collectionType = new TypeToken<ArrayList<Project>>(){}.getType();
//JSON expects an list so can't use our ArrayList from the lstart
List<Project> lst= new Gson().fromJson(response, collectionType);
//Now that we have that list lets add it to the ArrayList which will hold our items.
for(Project l : lst)
{
prjcts.add(l);
ConstantData.projectsList.add(l);
}
//Since we've modified the arrayList we now need to notify the adapter that
//its data has changed so that it updates the UI
arrayAdapter.notifyDataSetChanged();
}
catch(Exception e)
{
Log.d("Error: ", e.getMessage());
}
}
lstTest.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent care = new Intent(ProjectsList.this, ProjectDetail.class);
care.putExtra("spendino.de.ProjectDetail.position",position);
startActivity(care);
}
});
}
#Override
public void onDestroy()
{
yAdapter.imageLoader.stopThread();
lstTest.setAdapter(null);
super.onDestroy();
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
return true;
} else {
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
alertbox.setTitle("spendino Helfomat");
alertbox.setMessage ("Please check your internet connection");
alertbox.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//Main.this.finish();
}
});
alertbox.show();
return false;
}
}
}
SharedPreferences has no methods for saving a JSON object as is, you must try to convert it to a String. Then when getting it you must parse this String back to JSON. Good luck!
JSON to String:
JSONObject o = new JSONObject(data.trim());
String name = o.getString(Constants.NAME);
long date = o.getLong(Constants.DATE);
String mes = o.getString(Constants.MESSAGE);
StringBuilder buf = new StringBuilder(text.getText());
buf.append(name).append(" (").append(dfTime.format(new Date(date))).append(")\n").append(mes).append("\n");
text.setText(buf.toString());
Making a JSON from a String is not a harder task, use StringTokenizer. Good luck!

Categories

Resources