Android - Pull to refresh within a tabbed fragment - android

I'm trying to make a refresh while sliding down on the top of the listview possible. I followed this link to make it work and it does on an activty. But I need it on fragments that are tabbed within a main activity so I cannot as the example shows use this method on my fragments.
Here's the correct code while using an activity:
TestActivity.java
import java.util.ArrayList;
import java.util.List;
import uk.co.senab.actionbarpulltorefresh.library.ActionBarPullToRefresh;
import uk.co.senab.actionbarpulltorefresh.library.PullToRefreshLayout;
import uk.co.senab.actionbarpulltorefresh.library.listeners.OnRefreshListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Fragment;
import android.app.ListFragment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
public class TestActivity extends BaseActivity {
#Override
protected Fragment getSampleFragment() {
return new SimpleListFragment();
}
public static class SimpleListFragment extends ListFragment implements
OnRefreshListener {
int i = 0;
private PullToRefreshLayout mPullToRefreshLayout;
ArrayAdapter<String> adapter;
List<String> list;
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onViewCreated(view, savedInstanceState);
list = new ArrayList<String>();
int no = 1;
for (int i = 0; i < 5; i++) {
list.add("Item No :" + no++);
}
super.onViewCreated(view, savedInstanceState);
ViewGroup viewGroup = (ViewGroup) view;
// As we're using a ListFragment we create a PullToRefreshLayout
// manually
mPullToRefreshLayout = new PullToRefreshLayout(
viewGroup.getContext());
// We can now setup the PullToRefreshLayout
ActionBarPullToRefresh
.from(getActivity())
// We need to insert the PullToRefreshLayout into the
// Fragment's ViewGroup
.insertLayoutInto(viewGroup)
// Here we mark just the ListView and it's Empty View as
// pullable
.theseChildrenArePullable(android.R.id.list,
android.R.id.empty).listener(this)
.setup(mPullToRefreshLayout);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, list);
// Set the List Adapter to display the sample items
setListAdapter(adapter);
setListShownNoAnimation(true);
}
#Override
public void onRefreshStarted(View view) {
// TODO Auto-generated method stub
// setListShown(false); // This will hide the listview and visible a
// round progress bar
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(5000); // 5 seconds
int itemNo = list.size();
itemNo++;
list.add("New Item No :" + itemNo);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
adapter.notifyDataSetChanged();
// Notify PullToRefreshLayout that the refresh has finished
mPullToRefreshLayout.setRefreshComplete();
// if you set the "setListShown(false)" then you have to
// uncomment the below code segment
// if (getView() != null) {
// // Show the list again
// setListShown(true);
// }
}
}.execute();
}
}
}
I've already tried multiple times to make this method work in my fragment code but I cannot succeed. The code below is a working fragment example without any input of the TestActivity.
InfoFragment.java
import java.util.ArrayList;
import java.util.List;
import com.example.app.Config;
...
import android.app.Activity;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
public class TicketInfoFragment extends Fragment {
List<Info> ticketInfo;
TicketFull ticket = new TicketFull();
private DatabaseHelper db;
int ticketId = TicketActivity.getCurrentTicketId();
String androidId;
String authCode;
String platform_url;
int uId;
View rootView;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
db = new DatabaseHelper(getActivity());
androidId = Secure.getString(getActivity().getContentResolver(),
Secure.ANDROID_ID);
Config config = new Config();
config = db.getConfig(androidId);
authCode = config.getAuthCode();
platform_url = config.getPlatformURL();
uId = config.getuId();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_ticket_information, container, false);
fillTicket();
return rootView;
}
private void fillTicket() {
HttpReader httpReader = new HttpReader();
httpReader
.setOnResultReadyListener(new HttpReader.OnResultReadyListener() {
#Override
public void resultReady(String result) {
JsonHelper jsonHelper = new JsonHelper();
ticket = jsonHelper.getTicket(result);
//showTicket();
fillSettings();
}
});
httpReader
.execute("http://aa.domainlink.com:1324/example/API/v1/json.php?auth=example&a=ticket&uauth="
+ authCode + "&uid=" + uId + "&id=" + ticketId);
}
private void readSettings() {
InfoAdapter infoAdapter = new InfoAdapter(
getActivity(), ticketInfo);
final ListView listViewInfo = (ListView) rootView.findViewById(R.id.listViewInfo);
listViewInfo.setAdapter(infoAdapter);
listViewInfo
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parentView,
View childView, int position, long id) {
}
});
listViewInfo.setEmptyView(rootView.findViewById(R.id.empty));
}
private void fillSettings() {
String dueDate = getString(R.string.noDueDate);
ticketInfo = new ArrayList<Info>();
ticketInfo.add(new Info(getString(R.string.ticket_subject), ticket.getSubject() + ""));
ticketInfo.add(new Info(getString(R.string.ticket_relation), ticket.getRelation() + ""));
ticketInfo.add(new Info(getString(R.string.ticket_status), ticket.getStatus() + ""));
ticketInfo.add(new Info(getString(R.string.ticket_priority), ticket.getPriority() + ""));
ticketInfo.add(new Info(getString(R.string.ticket_created), ticket.getTicketCreate() + ""));
ticketInfo.add(new Info(getString(R.string.ticket_department), ticket.getDepartmentName() + ""));
ticketInfo.add(new Info(getString(R.string.ticket_user), ticket.getUser() + ""));
if (!ticket.getDueDate().equals("00-00-0000 00:00:00")) {
dueDate = ticket.getDueDate();
}
ticketInfo.add(new Info(getString(R.string.ticket_dueDate), dueDate));
readSettings();
}
}
The BaseActivity that the activity normally requires:
BaseActivity.java
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class BaseActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// Add the Sample Fragment if there is one
Fragment sampleFragment = getSampleFragment();
if (sampleFragment != null) {
getFragmentManager().beginTransaction()
.replace(android.R.id.content, sampleFragment).commit();
}
}
//This method will override by child class. Then base class can get the fragment
protected Fragment getSampleFragment() {
return null;
}
}
Posting my failed tries on implementing the activity method in my fragments would not work I guess so I do not post them.
If anyone of you could help thanks alot.

Android SDK has finally added SwipeRefreshLayout. Maybe you can add this to your layout?
http://developer.android.com/reference/android/support/v4/widget/SwipeRefreshLayout.html

Related

How to use ViewPager + Fragment +ListView

here is my Code,the Activityis to show 7 tabs from Mon. to Sun.each tabs use the same fragment,I wanna add a ListView to load the imformation,but I don't how to do
Activity:
package space.levan.myclass.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.Bind;
import butterknife.ButterKnife;
import it.neokree.materialtabs.MaterialTab;
import it.neokree.materialtabs.MaterialTabHost;
import it.neokree.materialtabs.MaterialTabListener;
import space.levan.myclass.R;
import space.levan.myclass.fragment.LessonFragment;
import space.levan.myclass.utils.InfoUtil;
import space.levan.myclass.utils.NetUtil;
/**
* Created by 339 on 2016/5/3.
*/
public class ScheduleActivity extends AppCompatActivity implements MaterialTabListener{
#Bind(R.id.materialTabHost)
MaterialTabHost mTabHost;
#Bind(R.id.pager)
ViewPager mViewPager;
ViewPagerAdapter adapter;
private List<HashMap<String, Object>> ClassInfos;
private HashMap<String, Object> ClassInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schedule);
ButterKnife.bind(this);
setTitle("课程表");
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
Fragment lessonFragment;
adapter = new ViewPagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(adapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// when user do a swipe the selected tab change
mTabHost.setSelectedNavigationItem(position);
}
});
// insert all tabs from pagerAdapter data
for (int i = 0; i < adapter.getCount(); i++) {
mTabHost.addTab(
mTabHost.newTab()
.setText(adapter.getPageTitle(i))
.setTabListener(this)
);
}
Calendar calendar = Calendar.getInstance();
int temp = calendar.get(Calendar.DAY_OF_WEEK) - 2;
mViewPager.setCurrentItem(temp);
Map<String, String> loginInfo = InfoUtil.getLoginInfo(ScheduleActivity.this);
getLesson(loginInfo.get("StuToken"));
}
public String getLesson(final String mToken) {
new Thread() {
public void run() {
String result = NetUtil.getSchedule(mToken);
if (result != null) {
try {
JSONObject jsonObject = new JSONObject(result);
int error = jsonObject.getInt("error");
String message = jsonObject.getString("message");
switch (error) {
case 0:
getDes(jsonObject);
break;
case 1:
showToast(message);
break;
case 2:
reLogin();
break;
default:
break;
}
}catch (Exception e) {
e.printStackTrace();
}
} else {
showToast("数据异常");
}
}
}.start();
return null;
}
private void getDes(JSONObject jsonObject) {
try {
JSONObject Object = jsonObject.getJSONObject("data");
JSONObject data = Object.getJSONObject("data");
for (int i = 1; i < 7; i++) {
JSONObject day = data.getJSONObject(""+i);
for (int n = 1; n < 5; n++) {
JSONArray lesson = day.getJSONArray(""+n);
ClassInfos = new ArrayList<>();
for(int m = 0; m < lesson.length();m++) {
JSONObject des = (JSONObject) lesson.get(m);
String name = des.getString("course");
String teacher = des.getString("teacher");
String time = des.getString("time");
String room = des.getString("classroom");
/*showToast("星期:" + i + "\n节次:" + n + "\n课程名字:"
+ name + "\n任课老师:" + teacher + "\n上课周数:" + time
+ "\n教室:" + room);*/
ClassInfo = new HashMap<>();
ClassInfo.put("Name","课程名字:" + name);
ClassInfo.put("Teacher","上课老师:" + teacher);
ClassInfo.put("Time","上课周次:" + time);
ClassInfo.put("Room","上课教室:" + room);
ClassInfos.add(ClassInfo);
}
}
}
}catch (JSONException e) {
e.printStackTrace();
}
}
private void showToast(final String message) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(ScheduleActivity.this,message, Toast.LENGTH_SHORT).show();
}
});
}
private void reLogin() {
InfoUtil.deleteUserInfo(ScheduleActivity.this);
runOnUiThread(new Runnable() {
#Override
public void run() {
final Intent intent = getPackageManager().
getLaunchIntentForPackage(getPackageName());
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
Toast.makeText(ScheduleActivity.this,
"数据异常,请重新登录帐号",Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onTabSelected(MaterialTab tab) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(MaterialTab tab) {
}
#Override
public void onTabUnselected(MaterialTab tab) {
}
private class ViewPagerAdapter extends FragmentStatePagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public Fragment getItem(int num) {
return new LessonFragment();
}
#Override
public int getCount() {
return 7;
}
#Override
public CharSequence getPageTitle(int position) {
int temp = position+1;
return "星期" + temp;
}
}
#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);
menu.add(0, 1, 0, R.string.home_about);
return true;
}
/**
* 用于界面返回按钮
* #param item
* #return
*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
break;
case 1:
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
}
Here is fragment :
package space.levan.myclass.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by 339 on 2016/5/5.
*/
public class LessonFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
TextView text = new TextView(container.getContext());
text.setText("(╯°Д°)╯︵┴┴");
text.setGravity(Gravity.CENTER);
return text;
}
}
You just need to add a ListView in the LessonFragment.
Follow these steps:
Create a layout file with a listview.
Inflate this layout in onCreateView method of LessonFragment and find this listview.
now, set an adapter for this listview, with the data you want.(hoping you know how to set an adapter)
And now you have a listview in each tab.
public class LessonFragment extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment_lesson, container, false);
mListView = (ListView) rootView.findViewById(R.id.listview);
//create an adapter
//set the above adapter to the listview
return rootView;
}
}

Loading in Android ListView stucked like forever

I'm new to android programming and I'm practicing in making a Facebook app. I got this ListView and which i will be using to display some information i got from facebook. But the problem is when the Listview starts to load the datas its stucked in the loading part and its taking forever but theres no error in the codes. here are the codes:
package com.example.forwardjunction;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphObject;
public class FragmentLayout extends Activity {
ProgressDialog mDialog;
static String postMessage;
static String from;
static String timeCreated;
static String postId;
static ArrayList<HashMap<String, String>> feedList;
private static final String TAG_MESSAGE = "message";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
static ListView list;
TextView author, feedMessage;
static UiLifecycleHelper uiHelper;
public FragmentLayout() {
// TODO Auto-generated constructor stub
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_layout);
author = (TextView) findViewById(R.id.author);
feedMessage = (TextView) findViewById(R.id.message);
feedList = new ArrayList<HashMap<String, String>>();
uiHelper = new UiLifecycleHelper(this, statusCallback);
// list = (ListView) findViewById(R.id.list);
}
public static class TitlesFragment extends ListFragment {
boolean mDualPane;
int mCurCheckPosition = 0;
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
//
// return null;
// }
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ListView list = getListView();
feedList = new ArrayList<HashMap<String, String>>();
Request loadPageFeed = new Request(Session.getActiveSession(),
"163340583656/posts", null, HttpMethod.GET,
new Request.Callback() {
#Override
public void onCompleted(Response response) {
// TODO Auto-generated method stub
Log.i("FEED RESPONSE", response.toString());
try {
GraphObject graphObj = response.getGraphObject();
JSONObject json = graphObj.getInnerJSONObject();
JSONArray jArray = json.getJSONArray("data");
for (int i = 0; i < jArray.length(); i++) {
JSONObject currObj = jArray.getJSONObject(i);
postId = currObj.getString("id");
if (currObj.has("message")) {
postMessage = currObj.getString("message");
} else if (currObj.has("story")) {
postMessage = currObj.getString("story");
} else {
postMessage = "Forward Publication has posted something.";
}
JSONObject fromObj = currObj
.getJSONObject("from");
from = fromObj.getString("name");
timeCreated = currObj
.getString("created_time");
HashMap<String, String> feed = new HashMap<String, String>();
feed.put(TAG_ID, postId);
feed.put(TAG_MESSAGE, postMessage);
feed.put(TAG_NAME, from);
Log.i("passed", feed.toString());
feedList.add(feed);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
loadPageFeed.executeAsync();
BaseAdapter adapter = new SimpleAdapter(getActivity(), feedList,
R.layout.feed_item, new String[] { TAG_MESSAGE, TAG_NAME,
TAG_ID }, new int[] { R.id.message, R.id.author,
R.id.id_tv });
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
View detailsFrame = getActivity(). findViewById(R.id.details);
mDualPane = detailsFrame != null
&& detailsFrame.getVisibility() == View.VISIBLE;
if (savedInstanceState != null) {
// Restore last state for checked position.
mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
}
if (mDualPane) {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
showDetails(mCurCheckPosition);
} else {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
getListView().setItemChecked(mCurCheckPosition, true);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curChoice", mCurCheckPosition);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
showDetails(position);
}
void showDetails(int index) {
mCurCheckPosition = index;
if (mDualPane) {
getListView().setItemChecked(index, true);
DetailsFragment details = (DetailsFragment) getFragmentManager()
.findFragmentById(R.id.details);
if (details == null || details.getShownIndex() != index) {
details = DetailsFragment.newInstance(index);
FragmentTransaction ft = getFragmentManager()
.beginTransaction();
ft.replace(R.id.details, details);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
} else {
Intent intent = new Intent();
intent.setClass(getActivity(), DetailsActivity.class);
intent.putExtra("index", index);
startActivity(intent);
}
}
}
public static class DetailsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
finish();
return;
}
if (savedInstanceState == null) {
DetailsFragment details = new DetailsFragment();
details.setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction()
.add(android.R.id.content, details).commit();
}
}
}
public static class DetailsFragment extends Fragment {
public static DetailsFragment newInstance(int index) {
DetailsFragment f = new DetailsFragment();
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
public int getShownIndex() {
return getArguments().getInt("index", 0);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ScrollView scroller = new ScrollView(getActivity());
TextView text = new TextView(getActivity());
int padding = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, 4, getActivity()
.getResources().getDisplayMetrics());
text.setPadding(padding, padding, padding, padding);
scroller.addView(text);
// text.setText(Shakespeare.DIALOGUE[getShownIndex()]);
return scroller;
}
}
#Override
public void onResume() {
super.onResume();
uiHelper.onResume();
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onSaveInstanceState(Bundle savedState) {
super.onSaveInstanceState(savedState);
uiHelper.onSaveInstanceState(savedState);
}
private Session.StatusCallback statusCallback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (state.isOpened()) {
Log.d("FacebookSampleActivity", "Facebook session opened");
} else if (state.isClosed()) {
Log.d("FacebookSampleActivity", "Facebook session closed");
}
}
};
}
And heres the xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="#+id/titles"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.example.forwardjunction.FragmentLayout$TitlesFragment" />
</FrameLayout>
I hope you can help me. cheers
*edit> I think the problem is that the listview is empty, i dont really know where the problem is
because the UI thread is Blocked
Rather than using your thread class use Asynctask
class xyz extends Asynctask
{
}
then add to overrididen methods
do in background
on post execute
I m posting the sample code of mine
package com.example.urlconnectionclass;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
ProgressDialog pDialog;
String urlString="http://api.androidhive.info/contacts/";
TextView tc;
String s;
JSONArray jr;
JSONObject jb,jb2;
ArrayList<HashMap<String, String>> contact;
String tagid="id";
String tagname="name",tagemail="email",taggender="gender",tagadd="address";
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=(ListView)findViewById(R.id.listView1);
contact = new ArrayList<HashMap<String,String>>();
new urlconn().execute();
}
#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;
}
public class urlconn extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
URL url= new URL(urlString);
HttpURLConnection conn =(HttpURLConnection)url.openConnection();
conn.connect();
InputStream is= conn.getInputStream();
s=convertStreamToString(is);
jb = new JSONObject(s);
jr= jb.getJSONArray("contacts");
for(int i=0;i<=jr.length();i++)
{
jb2=jr.getJSONObject(i);
String id=jb2.getString(tagid);
String name=jb2.getString(tagname);
String email=jb2.getString(tagemail);
String address=jb2.getString(tagadd);
String gender=jb2.getString("gender");
HashMap<String, String> map = new HashMap<String, String>();
map.put(tagid, id);
map.put(tagname, name);
map.put(tagemail, email);
map.put("gender", gender);
map.put(tagadd, address);
contact.add(map);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
String [] sr={tagid,tagname,tagemail,"gender",tagadd};
int [] in= {R.id.textView1,R.id.textView2,R.id.textView3,R.id.textView4,R.id.textView5};
SimpleAdapter sa= new SimpleAdapter(MainActivity.this, contact, R.layout.mapxml,sr, in);
lv.setAdapter(sa);
}
public String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
}
}

Grid-view is not formed in horizontal-scrolling-pages like home screen when app is in Background or Process is died

I am developing Horizontal Scrolling pages and tabs
MY app is working well in all devices in foreground, but when it goes to background, after one hour, the logs saying that Process com.example.myapp has died. When i reopen the app , the gridview data is not appearing but when scrolling horizontally , getView() method displaying all data like images and text.
that means app has data but view is not formed when process has died. And if i press back button and re-open the app, It is working good
My MainActivity.java is here
package com.bbgusa.bbgdemo.ui.phone;
import java.util.List;
import java.util.Vector;
import org.json.JSONObject;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.TabHost;
import com.bbgusa.bbgdemo.R;
import com.bbgusa.bbgdemo.listener.phone.CustomViewPager;
import com.bbgusa.bbgdemo.ui.chat.phone.ChatFragmentTab;
import com.bbgusa.bbgdemo.ui.dialpad.phone.DialerFragment;
import com.bbgusa.bbgdemo.ui.home.phone.AlarmFragmentPhone;
import com.bbgusa.bbgdemo.ui.home.phone.HomeFragment;
import com.bbgusa.bbgdemo.ui.home.phone.HomeFragmentTab;
import com.bbgusa.bbgdemo.ui.home.phone.InfoFragPhone;
import com.bbgusa.bbgdemo.ui.home.phone.MapPhone;
import com.bbgusa.bbgdemo.ui.home.phone.WeatherFragmentPhone;
import com.bbgusa.bbgdemo.ui.messages.phone.MessagesFragment;
import com.bbgusa.bbgdemo.ui.settings.phone.AboutFragment;
import com.bbgusa.bbgdemo.ui.tablet.ConstantsManager;
import com.bbgusa.bbgdemo.ui.tablet.OnFragmentChangedListenerPhone;
import com.bbgusa.bbgdemo.utils.common.UConnectUtils;
public class MainActivity extends FragmentActivity implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener, OnFragmentChangedListenerPhone {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_phone);
this.initialiseTabHost(savedInstanceState);
initialiseViewPager();
}
/**
* Initialise ViewPager
*/
private void initialiseViewPager() {
List<Fragment> fragments = new Vector<Fragment>();
fragments.add(Fragment.instantiate(this,HomeFragmentTab.class.getName()));
fragments.add(Fragment.instantiate(this, DialerFragment.class.getName()));
fragments.add(Fragment.instantiate(this,MessagesFragment.class.getName()));
fragments.add(Fragment.instantiate(this,ChatFragmentTab.class.getName()));
fragments.add(Fragment.instantiate(this, AboutFragment.class.getName()));
this.mPagerAdapter = new PagerAdapter(super.getSupportFragmentManager(), fragments);
this.mViewPager = (CustomViewPager) findViewById(R.id.tabviewpager);
this.mViewPager.setAdapter(this.mPagerAdapter);
this.mViewPager.setOnPageChangeListener(this);
this.mViewPager.setOffscreenPageLimit(5);
this.mViewPager.setCurrentItem(0);
}
#Override
public void onFragmentChangePhone(JSONObject response, String whichView, String title, String mPhoneNo) {
Bundle b = new Bundle();
if(response != null)
b.putString("JSONObject", response.toString());
if(title != null)
b.putString("Title", title);
String propertyId = UConnectUtils.getPropertyId(mPref, getString(R.string.property_id));
b.putString(UConnectUtils.PROPERTY_ID_KEY, propertyId);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
Fragment fragment = null;
if (whichView.equals(ConstantsManager.GRIDVIEWPAGER)) {
// getSupportFragmentManager().popBackStack();
fragment = new HomeFragment();
} else if (whichView.equals(ConstantsManager.WEATHER)) {
fragment = new WeatherFragmentPhone();
}else if (whichView.equals(ConstantsManager.ALARM)) {
fragment = new AlarmFragmentPhone();
}else if (whichView.equals(ConstantsManager.MAPS)) {
fragment = new MapPhone();
}else if (whichView.equals(ConstantsManager.HELP)) {
fragment = new InfoFragPhone();
}
if (whichView.equals(ConstantsManager.MAPS)) { // to show plus-icon on map top right corner
HomeFragment.getInstance().onGridViewVisibilityChanged(true);
HomeFragmentTab.getInstance().onFragmentTabChange(View.VISIBLE , title, "", View.VISIBLE);
} else if (!whichView.equals(ConstantsManager.GRIDVIEWPAGER)) {
HomeFragment.getInstance().onGridViewVisibilityChanged(true);
HomeFragmentTab.getInstance().onFragmentTabChange(View.VISIBLE , title, mPhoneNo, View.GONE);
}
fragment.setArguments(b);
ft.add(R.id.main_home_frag, fragment);
if (whichView.equals(ConstantsManager.GRIDVIEWPAGER)) {
fragmentManager.popBackStack();
} else {
ft.addToBackStack(fragment.toString());
}
ft.commit();
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onTabChanged(String tabId) {
// TODO Auto-generated method stub
}
}
and my HomeFragmentTab.java is
package com.bbgusa.bbgdemo.ui.home.phone;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bbgusa.bbgdemo.R;
import com.bbgusa.bbgdemo.ui.phone.MainActivity;
import com.bbgusa.bbgdemo.ui.tablet.ConstantsManager;
import com.bbgusa.bbgdemo.ui.tablet.OnFragmentTabChangedListener;
#SuppressLint("NewApi")
public class HomeFragmentTab extends Fragment implements OnFragmentTabChangedListener{
private static final String TAG = HomeFragmentTab.class.getSimpleName();
private static HomeFragmentTab tab;
private MainActivity activityPhone;
public static HomeFragmentTab getInstance() {
return tab;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
activityPhone = (MainActivity) activity;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v;
if (container == null) {
return null;
}
Log.i(TAG, "onCreateView");
v = inflater.inflate(R.layout.hometab_phone, container, false);
tab = this;
activityPhone.onFragmentChangePhone(null, ConstantsManager.GRIDVIEWPAGER, getResources().getString(R.string.app_name), "");
return v;
}
#Override
public void onFragmentTabChange(int i, String title, String mPhoneNo, int mapV) {
}
}
and HomeFragment.java is
package com.bbgusa.bbgdemo.ui.home.phone;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.bbgusa.bbgdemo.R;
import com.bbgusa.bbgdemo.ui.ImageCacheManager;
import com.bbgusa.bbgdemo.ui.cms.tablet.TestTopics;
import com.bbgusa.bbgdemo.ui.cms.tablet.TopicList;
import com.bbgusa.bbgdemo.ui.phone.MainActivity;
import com.bbgusa.bbgdemo.ui.tablet.onGridViewVisibilityChangedListener;
import com.bbgusa.bbgdemo.utils.common.UCConstants;
import com.bbgusa.bbgdemo.utils.common.UConnectUtils;
import com.viewpagerindicator.IconPageIndicator;
import com.viewpagerindicator.IconPagerAdapter;
import com.viewpagerindicator.PageIndicator;
public class HomeFragment extends Fragment implements onGridViewVisibilityChangedListener{
private static final String TAG = HomeFragment.class.getSimpleName();
private ViewPager mViewPager;
private MainActivity activity;
private PageIndicator mIndicator;
private Animation mRotateAnim;
private Dialog indiacatorDialog;
private LinearLayout homeFragmentLL;
private static HomeFragment homeFragment;
public static final HomeFragment getInstance() {
return homeFragment;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = (MainActivity) activity;
}
#Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "onCreate");
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (container == null) {
return null;
}
View v = inflater.inflate(R.layout.home_phone, container, false);
homeFragment = this;
UConnectUtils.setLauncher(true);
mViewPager = (ViewPager) v.findViewById(R.id.viewpager);
mIndicator = (IconPageIndicator) v.findViewById(R.id.indicator);
homeFragmentLL = (LinearLayout) v.findViewById(R.id.homeFragment);
indiacatorDialog = new Dialog(getActivity());
indiacatorDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
indiacatorDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
indiacatorDialog.setContentView(R.layout.indicator_dialog);
indiacatorDialog.setCanceledOnTouchOutside(false);
Window window = indiacatorDialog.getWindow();
window.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
mRotateAnim = AnimationUtils.loadAnimation(getActivity(), R.anim.rotate_and_scale);
UConnectUtils.addAnimationFrameCount(mRotateAnim);
indicatorAnim();
// for property id
// if (activity.isInterNetAvailable()) {
Log.i(TAG, "onCreateView========== isInterNetAvailable");
new CmsPropertyAsync(activity).execute(UCConstants.CMS_CONFIG_URL, UCConstants.CMS_CONFIG_KEY);
// }
return v;
}
protected void parseJson(JSONObject rootResponce) {
TestTopics.imageUrls.clear();
TestTopics.titles.clear();
TestTopics.mMainMenuID.clear();
TestTopics.mViewType.clear();
TestTopics.mPhoneNo.clear();
try {
//get the Version
String version = rootResponce.optString("VERSION");
SharedPreferences mPref;
SharedPreferences.Editor edit;
mPref = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
edit = mPref.edit();
edit.putString(getResources().getString(R.string.pref_cms_version_key), version).commit();
JSONArray jsonArray = rootResponce.getJSONArray("MAINMENU");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject childMenuObject = jsonArray.getJSONObject(i);
int mainMenuID = childMenuObject.optInt("mainMenuId");
String title = childMenuObject.optString("title");
String viewType = childMenuObject.optString("viewType");
String imageUrl = childMenuObject.optString("imageUrl");
String phoneNo = childMenuObject.optString("phoneNo");
TestTopics.mMainMenuID.add(mainMenuID);
TestTopics.imageUrls.add(imageUrl);
TestTopics.titles.add(title);
TestTopics.mViewType.add(viewType);
TestTopics.mPhoneNo.add(phoneNo);
}
// Create a TopicList for this demo. Save it as the shared instance
// in
// TopicList
String sampleText = getResources().getString(R.string.sample_topic_text);
TopicList tlist = new TopicList(sampleText);
TopicList.setInstance(tlist);
// Create an adapter object that creates the fragments that we need
// to display the images and titles of all the topics.
MyAdapter mAdapter = new MyAdapter(getActivity().getSupportFragmentManager(), tlist, getResources());
// mViewPager.removeAllViews();
mViewPager.setAdapter(mAdapter);
// mViewPager.setPageTransformer(true, new DepthPageTransformer());
mIndicator.setViewPager(mViewPager);
mIndicator.setCurrentItem(0);
mIndicator.notifyDataSetChanged();
ViewTreeObserver observer = mViewPager.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
#Override
public void onGlobalLayout() {
mViewPager.bringChildToFront(mViewPager.getChildAt(0));
if(Build.VERSION.SDK_INT >= UCConstants.ICE_CREAM_SANDWICH_MR1){
mViewPager.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}else{
mViewPager.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}
});
/*Fragment f = new GridViewFragment();
FragmentTransaction t = getFragmentManager().beginTransaction();
t.replace(R.id.main_home_frag, f);
t.commit();*/
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Adapter class
*
* This adapter class sets up GridFragment objects to be displayed by a
* ViewPager.
*/
public static class MyAdapter extends FragmentStatePagerAdapter implements IconPagerAdapter {
private TopicList mTopicList;
private int mNumItems = 0;
private int mNumFragments = 0;
/**
* Return a new adapter.
*/
public MyAdapter(FragmentManager fm, TopicList db, Resources res) {
super(fm);
setup(db, res);
}
/**
* Get the number of fragments to be displayed in the ViewPager.
*/
#Override
public int getCount() {
Log.i(TAG, "getCount : mNumFragments = "+mNumFragments);
return mNumFragments;
}
/**
* Return a new GridFragment that is used to display n items at the
* position given.
*
* #param position
* int - the position of the fragement; 0..numFragments-1
*/
#Override
public Fragment getItem(int position) {
// Create a new Fragment and supply the fragment number, image
// position, and image count as arguments.
// (This was how arguments were handled in the original pager
// example.)
Bundle args = new Bundle();
args.putInt("num", position + 1);
args.putInt("firstImage", position * mNumItems);
// The last page might not have the full number of items.
int imageCount = mNumItems;
if (position == (mNumFragments - 1)) {
int numTopics = mTopicList.getNumTopics();
int rem = numTopics % mNumItems;
if (rem > 0)
imageCount = rem;
}
args.putInt("imageCount", imageCount);
args.putSerializable("topicList", TopicList.getInstance());
// Return a new GridFragment object.
Log.i(TAG, "created fragmenat number:==== "+position+" "+1);
GridViewFragmentPhone f = new GridViewFragmentPhone();
f.setArguments(args);
Log.i(TAG, "getItem : imageCount = "+imageCount);
return f;
}
/**
* Set up the adapter using information from a TopicList and resources
* object. When this method completes, all the instance variables of the
* adapter are valid;
*
* #param tlist
* TopicList
* #param res
* Resources
* #return void
*/
void setup(TopicList tlist, Resources res) {
mTopicList = tlist;
if ((tlist == null) || (res == null)) {
mNumItems = 2;//DEFAULT_NUM_ITEMS;
mNumFragments = 2;//DEFAULT_NUM_FRAGMENTS;
} else {
int numTopics = tlist.getNumTopics();
int numRowsGV = res.getInteger(R.integer.num_of_rows_gridview);
int numColsGV = res.getInteger(R.integer.num_of_cols_gridview);
int numTopicsPerPage = numRowsGV * numColsGV;
int numFragments = numTopics / numTopicsPerPage;
if (numTopics % numTopicsPerPage != 0)
numFragments++; // Add one if there is a partial page
mNumFragments = numFragments;
mNumItems = numTopicsPerPage;
}
} // end setup
#Override
public int getIconResId(int index) {
int[] ICON = new int[mNumFragments];
for (int i = 0; i < mNumFragments; i++) {
ICON[i] = R.drawable.slidericon;
}
return ICON[index % ICON.length];
}
} // end class MyAdapter
#Override
public void onGridViewVisibilityChanged(boolean hide) {
if(hide){
homeFragmentLL.setVisibility(View.GONE);
}else {
homeFragmentLL.setVisibility(View.VISIBLE);
}
}
#Override
public void onDetach() {
super.onDetach();
activity = null;
}
#Override
public void onDestroy() {
super.onDestroy();
}
private class CmsPropertyAsync extends AsyncTask<String, Void, String> {
MainActivity context;
CmsPropertyAsync(MainActivity activityTab) {
context = activityTab;
}
#Override
protected String doInBackground(String... params) {
String propertyId = UConnectUtils.getPropertyId(PreferenceManager.getDefaultSharedPreferences(context),getResources().getString(R.string.property_id));
if(propertyId != null && propertyId.length() > 0){
return propertyId;
}
return UConnectUtils.requestPropertyId(params[0], params[1]);
}
#Override
protected void onPostExecute(String propertyId) {
if(propertyId == null){
indiacatorDialog.dismiss();
showPropertyIdTimeoutAlert(getActivity());
return;
}
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
editor.putString(getString(R.string.property_id),propertyId).commit();
String url = null;
String locale = Locale.getDefault().getLanguage();
url = UCConstants.CMS_BASE_URL+"mainMenu?propertyId="+propertyId+"&lang="+locale;
JsonObjectRequest jsObjRequest = new JsonObjectRequest(
Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
parseJson(response);
indiacatorDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (activity != null) {
// activity.getConnection(error);
}
indiacatorDialog.dismiss();
}
});
ImageCacheManager.getInstance().getQueueForMainmenu().add(jsObjRequest);
}
}
private void indicatorAnim() {
if (indiacatorDialog != null) {
ImageView alertIndicator = (ImageView) indiacatorDialog.findViewById(R.id.alert_indicator);
alertIndicator.startAnimation(mRotateAnim);
if (!getActivity().isFinishing()) {
indiacatorDialog.show();
}
}
}
// Show alert for Time out
private void showPropertyIdTimeoutAlert(final Activity context) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setIcon(R.drawable.alert_dialog_icon);
alertDialog.setTitle(context.getString(R.string.timeout_msg));
alertDialog.setMessage(context.getString(R.string.timeout_msg2));
alertDialog.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
indicatorAnim();
// for property id
new CmsPropertyAsync(activity).execute(UCConstants.CMS_CONFIG_URL, UCConstants.CMS_CONFIG_KEY);
}
});
alertDialog.setNegativeButton("Cancel", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
getActivity().finish();
}
});
AlertDialog alert = alertDialog.create();
alert.setCancelable(false);
alert.setCanceledOnTouchOutside(false);
if (context != null && !context.isFinishing()) {
alert.show();
}
}
}
Actually, some data is being saved with onSavedInstaceState(). The data is not being deleted when process has been killed on LowMemory.
I fixed this with
#Override
protected void onSaveInstanceState(Bundle outState) {
//super.onSaveInstanceState(outState);
}
Just do not call super class. Just comment like above

change the items in a ListView from another fragment

I have two fragments, lets call them Fragment A and Fragment B, which are a part of a NavigationDrawer (this is the activity they a bound to). In Fragment A I have a button. When this button is pressed, I would like another item added to the ListView in Fragment B.
What is the best way to do this? Use Intents, SavedPreferences, making something public(?) or something else?
EDIT 5: 20/7/13 This is with srains latest code
This is the NavigationDrawer that I use to start the fragments:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Navigation_Drawer extends FragmentActivity {
public DrawerLayout mDrawerLayout; // Creates a DrawerLayout called_.
public ListView mDrawerList;
public ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mNoterActivities; // This creates a string array called _.
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
// Just setting up the navigation drawer
} // End of onCreate
// Removed the menu
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
private void selectItem(int position) {
FragmentManager fragmentManager = getSupportFragmentManager();
if (position == 0) {
Fragment qnfragment = new QuickNoteFragment();
((FragmentBase) qnfragment).setContext(this);
Bundle args = new Bundle(); // Creates a bundle called args
args.putInt(QuickNoteFragment.ARG_nOTERACTIVITY_NUMBER, position);
qnfragment.setArguments(args);
fragmentManager.beginTransaction()
.replace(R.id.content_frame, qnfragment).commit();
} else if (position == 3) {
Fragment pendViewPager = new PendViewPager(); // This is a ViewPager that includes HistoryFragment
((FragmentBase) pendViewPager).setContext(this);
Bundle args = new Bundle();
pendViewPager.setArguments(args);
fragmentManager.beginTransaction()
.replace(R.id.content_frame, pendViewPager).commit();
}
// Update title etc
}
#Override
protected void onPostCreate(Bundle savedInstanceState) { // Used for the NavDrawer toggle
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) { // Used for the NavDrawer toggle
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
This is QuickNoteFragment:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class QuickNoteFragment extends FragmentBase implements OnClickListener {
public static final String ARG_nOTERACTIVITY_NUMBER = "noter_activity";
Button b_create;
// removed other defining stuff
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.quicknote, container, false);
int i = getArguments().getInt(ARG_nOTERACTIVITY_NUMBER);
String noter_activity = getResources().getStringArray(
R.array.noter_array)[i];
FragmentManager fm = getFragmentManager();
setRetainInstance(true);
b_create = (Button) rootView.findViewById(R.id.qn_b_create);
// Removed other stuff
getActivity().setTitle(noter_activity);
return rootView;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.qn_b_create:
String data = "String data";
DataModel.getInstance().addItem(data);
break;
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
}
}
public interface OnItemAddedHandler { // Srains code
public void onItemAdded(Object data);
}
}
This is HistoryFragment (Remember it is part of a ViewPager):
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.RiThBo.noter.QuickNoteFragment.OnItemAddedHandler;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class HistoryFragment extends FragmentBase implements OnItemAddedHandler {
ListView lv;
List<Map<String, String>> planetsList = new ArrayList<Map<String, String>>();
SimpleAdapter simpleAdpt;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.history, container, false);
initList();
ListView lv = (ListView) view.findViewById(R.id.listView);
simpleAdpt = new SimpleAdapter(getActivity(), planetsList,
android.R.layout.simple_list_item_1, new String[] { "planet" },
new int[] { android.R.id.text1 });
lv.setAdapter(simpleAdpt);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parentAdapter, View view,
int position, long id) {
// We know the View is a TextView so we can cast it
TextView clickedView = (TextView) view;
Toast.makeText(
getActivity(),
"Item with id [" + id + "] - Position [" + position
+ "] - Planet [" + clickedView.getText() + "]",
Toast.LENGTH_SHORT).show();
}
});
registerForContextMenu(lv);
return view;
}
private void initList() {
// We populate the planets
planetsList.add(createPlanet("planet", "Mercury"));
planetsList.add(createPlanet("planet", "Venus"));
planetsList.add(createPlanet("planet", "Mars"));
planetsList.add(createPlanet("planet", "Jupiter"));
planetsList.add(createPlanet("planet", "Saturn"));
planetsList.add(createPlanet("planet", "Uranus"));
planetsList.add(createPlanet("planet", "Neptune"));
}
private HashMap<String, String> createPlanet(String key, String name) {
HashMap<String, String> planet = new HashMap<String, String>();
planet.put(key, name);
return planet;
}
// We want to create a context Menu when the user long click on an item
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterContextMenuInfo aInfo = (AdapterContextMenuInfo) menuInfo;
// We know that each row in the adapter is a Map
HashMap map = (HashMap) simpleAdpt.getItem(aInfo.position);
menu.setHeaderTitle("Options for " + map.get("planet"));
menu.add(1, 1, 1, "Details");
menu.add(1, 2, 2, "Delete");
}
#Override
public void onItemAdded(Object data) {
// to add item
String string = String.valueOf(data);
Toast.makeText(getContext(), "Data: " + string, Toast.LENGTH_SHORT).show();
planetsList.add(createPlanet("planet", string));
}
#Override
public void onStart() {
super.onStart();
DataModel.getInstance().setOnItemAddedHandler(this);
}
}
This is FragmentBase:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
public class FragmentBase extends Fragment {
private FragmentActivity mActivity; // I changed it to FragmentActivity because Activity was not working, and my `NavDrawer` is a FragmentActivity.
public void setContext(FragmentActivity activity) {
mActivity = mActivity;
}
public FragmentActivity getContext() {
return mActivity;
}
}
This is DataModel:
import android.util.Log;
import com.xxx.xxx.QuickNoteFragment.OnItemAddedHandler;
public class DataModel {
private static DataModel instance;
private static OnItemAddedHandler mOnItemAddHandler;
public static DataModel getInstance() {
if (null == instance) {
instance = new DataModel();
}
return instance;
}
public void setOnItemAddedHandler(OnItemAddedHandler handler) {
mOnItemAddHandler = handler;
}
public void addItem(Object data) {
if (null != mOnItemAddHandler)
mOnItemAddHandler.onItemAdded(data);
else {
Log.i("is context null?", "yes!");
}
}
}
Thank you
I suggest you to use interface and MVC, that will make your code much more maintainable.
First you need an interface:
public interface OnItemAddedHandler {
public void onItemAdded(Object data);
}
Then, you will need a data model:
public class DataModel {
private static DataModel instance;
private static OnItemAddedHandler mOnItemAddHandler;
public static DataModel getInstance() {
if (null == instance) {
instance = new DataModel();
}
return instance;
}
public void setOnItemAddedHandler(OnItemAddedHandler handler) {
mOnItemAddHandler = handler;
}
public void addItem(Object data) {
if (null != mOnItemAddHandler)
mOnItemAddHandler.onItemAdded(data);
}
}
When you click the button, you can add data into the datamodel:
Object data = null;
DataModel.getInstance().addItem(data);
Then, the FragmentB implements the interface OnItemAddedHandler to add item
public class FragmentB implements OnItemAddedHandler {
#Override
public void onItemAdded(Object data) {
// to add item
}
}
also, When the FragmentB start, you should register itself to DataModel:
public class FragmentB implements OnItemAddedHandler {
#Override
public void onItemAdded(Object data) {
// to add item
}
#Override
protected void onStart() {
super.onStart();
DataModel.getInstance().setOnItemAddedHandler(this);
}
}
You also can add DataModel.getInstance().setOnItemAddedHandler(this); to the onCreate method of FragmentB
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DataModel.getInstance().setOnItemAddedHandler(this);
// do other things
}
update
you can send string simply:
String data = "some string";
DataModel.getInstance().addItem(data);
then on FragementB
public class FragmentB implements OnItemAddedHandler {
#Override
public void onItemAdded(Object data) {
// get what you send into method DataModel.getInstance().addItem(data);
String string = String.valueOf(data);
}
}
update
OK. You have add DataModel.getInstance().setOnItemAddedHandler(this) in onCreateView method, so there is no need to add it in onStart() method. You can remove the whole onStart method.
onStart will be called on the fragment start, we do not need to call it in onCreateView. And on onItemAdded will be call when call the method DataModel.getInstance().addItem(data), we do not need to call it in onCreateView neither.
so, you can remove the code below from onCreateView method:
DataModel.getInstance().setOnItemAddedHandler(this);
// remove the methods below
// onItemAdded(getView());
// onStart();
You have another fragment where there is a button, you can add the codes below in the clickhandler function:
String data = "some string";
DataModel.getInstance().addItem(data);
update3
I think the HistoryFragment has been detached after you when to QuickNoteFragment
You can add code to HistoryFragment to check:
#Override
public void onDetach() {
super.onDetach();
Log.i("test", String.format("onDetach! %s", getActivity() == null));
}
update4
I think HistoryFragment and QuickNoteFragment should has an parent class, named FragmentBase:
public class FragmentBase extends Fragment {
private Activity mActivity;
public void setContext(Activity activity) {
mActivity = mActivity;
}
public Activity getContext() {
return mActivity;
}
}
HistoryFragment and QuickNoteFragment extends FragmentBase. Then when you switch between them, you can call setContext to set a Activity, like:
private void selectItem(int position) {
FragmentManager fragmentManager = getSupportFragmentManager();
if (position == 0) {
Fragment qnfragment = new QuickNoteFragment();
qnfragment.setContext(this);
// ...
} else if (position == 1) {
Fragment pagerFragment = new RemViewPager();
pagerFragment.setContext(this);
// ...
}
}
now, we can get a non-null activity in HistoryFragment by calling getContext, so we can change onItemAdded method to:
#Override
public void onItemAdded(Object data) {
// to add item
String string = String.valueOf(data);
Toast.makeText(getContext(), "Data: " + string, Toast.LENGTH_SHORT).show();
planetsList.add(createPlanet("planet", string));
}
I hope this would work.
Some good design principals:
An activity can know everything pubic about any Fragment it contains.
A Fragment should not know anything about the specific Activities that contain it.
A Fragment should NEVER know about other fragments that may or may not be contained in the Parent activity.
A suggested approach (informal design pattern) based on these principles.
Each fragment should declare an interface to be implemented by its parent activity:
public class MyFragment extends Fragment
{
public interface Parent
{
void onMyFragmentSomeAction();
}
private Parent mParent;
public onAttach(Activity activity)
{
mParent = (Parent) activity;
}
// This would actually be in a listener. Simplifying to save typing.
void onSomeButtonClick(View button)
{
mParent.onMyFragmentSomeAction();
}
}
And the activity should implement the appropriate interfaces for all of its contained fragments.
public class MyActivity extends Activity
implements MyFragment.Parent,
YourFragment.Parent,
HisFragment.Parent
{
[usual Activity code]
void onMyFragmentSomeAction()
{
if yourFragment is showing
{
yourFragment.reactToSomeAction();
}
if hisFragment is showing
{
hisFragment.observeThatSomeActionHappened();
}
[etc]
}
The broadcast approach is good, too, but it's pretty heavyweight and it requires the target Fragment to know what broadcasts will be sent by the source Fragment.
Use Broadcast. Send a boradcast from A, and B will receive and handle it.
Add a public method to B, for example, public void addListItem(), which will add data to listview in B. Fragment A try to find the instance of Fragment B using FragmentMananger.findFragmentByTag() and invoke this method.

How to fetch data from Api into listview?

When i am trying to call the method "refresh" of main activity from another Api class,the method was called and also it shows some fatal errors.And it didn't change the adapter values.Can anyone give any idea to clear that.?
package com.example.hotspot;
import com.example.hotspot.HotspotApi;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.ListView;
import android.widget.TextView;
public class HotSpot extends Activity {
TextView textview;
ListView listview;
HotspotAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hot_spot);
textview = (TextView) findViewById(R.id.textView1);
listview = (ListView) findViewById(R.id.listView1);
adapter = new HotspotAdapter(this);
listview.setAdapter(adapter);
new HotspotApi(adapter).execute();
}
public void refresh() {
System.out.println("refresh() is called");
adapter.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.hot_spot, menu);
return true;
}
}
hotspot.java
package com.example.hotspot;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.hotspot.HotspotModel;
import com.example.hotspot.HotspotAdapter;
import android.os.AsyncTask;
public class HotspotApi extends AsyncTask<Void, Integer, Void> implements
Icommon {
public Boolean IsServerErr = false;
private JSONArray response_array;
String url = "some url";
HotspotAdapter adapter;
HotSpot hot;
public HotspotApi(HotspotAdapter adapter) {
this.adapter = adapter;
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
getresult();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
hot=new HotSpot();
hot.refresh();
super.onPostExecute(result);
}
void getresult() {
InternetManager manager = new InternetManager(url);
String category_jsonresponse = manager.URLRequest();
if (!manager.IsServerConn) {
IsServerErr = true;
}
if (category_jsonresponse != null) {
System.out.println("Hotspot_jsonresponse" + category_jsonresponse);
try {
response_array = new JSONArray(category_jsonresponse);
for (int i = 1; i < response_array.length(); i++) {
JSONObject image_object = response_array.getJSONObject(i);
HotspotModel h = new HotspotModel();
h.setId(image_object.getString("id") == null ? ""
: image_object.getString("id"));
h.setContent(image_object.getString("content") == null ? ""
: image_object.getString("content"));
h.setImg(image_object.getString("img") == null ? ""
: image_object.getString("img"));
h.setName(image_object.getString("name") == null ? ""
: image_object.getString("name"));
arraylist.add(h);
}
System.out.println("HotspotModelsize() is " + arraylist.size());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
HotspotAdapter.java
package com.example.hotspot;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class HotspotAdapter extends BaseAdapter implements Icommon{
private TextView textview;
private View view;
ImageView imageview;
private LayoutInflater inflater;
public HotspotAdapter(Context context ){
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arraylist.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arraylist.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
if (arg1 == null) {
view = inflater.inflate(R.layout.custom_layout, null);
} else {
view = arg1;
}
textview = (TextView) view.findViewById(R.id.txt_content);
textview.setText(arraylist.get(arg0).getName());
return view;
}
}
In your HotSpotApi class you are creating a new HotSpot activity, this seems wrong. I guess that you are getting json data from internet and load it into a listview.
Solution:
In HotspotApi change following instead of calling activity method:
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
adapter.notfiyDatasetChanged();
}
Hope this will help you.
hot=new HotSpot(); ?? you cannot use like that! HotSpot is an activity, should be called by Framework for example, activitymanager. Or use startActivity() to show a activity.
Refresh method (adapter.notifyDataSetChanged();) will result in refresh of UI. However, hot = new HotSpot() will not call onCreated() method,which means the UI is not created. So it definitely results in the fatal error.
I'd never see anyone call an Activity with new operator.
You should reference the common process about how use a activity and adapter.

Categories

Resources