I have this app that shows a help with com.cleveroad.slidingtutorial library
I follow the documentation accord to android.app.Fragment
But I stuck with this error always when close or slide screen to the next pagefragment. I tried with 1 page and more and always get the same error Attempt to get length of null array
Version of slidingtutorial on gradle com.cleveroad:slidingtutorial:1.0.8
Sliding tutorial guide Cleveroad/SlidingTutorial-Android
MainActivityTutorialCrearContacto class
public class MainActivityTutorialCrearContacto extends Activity {
public UsuarioDao usuario;
public Typeface typeface_bold, typeface_regular;
private int[] mPagesColors;
private static final int TOTAL_PAGES = 1;
private static final int ACTUAL_PAGES_COUNT = 3;
private final String TAG = MainActivityTutorialCrearContacto.class.getSimpleName();
public static void start(Context context) {
context.startActivity(new Intent(context, MainActivityTutorialCrearContacto.class));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_tutorial);
Context ctx = getApplicationContext();
try {
typeface_regular = Typeface.createFromAsset(ctx.getAssets(), Constantes.TYPEFACE_FONT_OPENSANS_REGULAR);
typeface_bold = Typeface.createFromAsset(ctx.getAssets(), Constantes.TYPEFACE_FONT_OPENSANS_SEMIBOLD);
} catch (Exception e) {
e.printStackTrace();
}
mPagesColors = new int[]{
getResources().getColor(R.color.color_fondo_green_dark)
// ,getResources().getColor(R.color.colorPrimaryDark)
// ,getResources().getColor(R.color.color_fondo_orange_pido )
};
if (savedInstanceState == null) {
replaceTutorialFragment();
}
}
final TutorialPageProvider<Fragment> tutorialPageProvider = new TutorialPageProvider<Fragment>() {
#NonNull
#Override
public Fragment providePage(int position) {
switch (position) {
case 0: {
return new ContactoFirstragment();
}
case 1: {
return new ContactoFirstragment();
}
case 2: {
return new ContactoThirdFragment();
}
default: {
throw new IllegalArgumentException("Unknown position: " + position);
}
}
}
};
public void replaceTutorialFragment() {
try {
final IndicatorOptions indicatorOptions = IndicatorOptions.newBuilder(this)
.build();
final TutorialOptions tutorialOptions = TutorialFragment.newTutorialOptionsBuilder(this)
.setUseAutoRemoveTutorialFragment(false)
.setUseInfiniteScroll(false)
.setPagesColors(mPagesColors)
.setPagesCount(TOTAL_PAGES)
.setIndicatorOptions(indicatorOptions)
.setTutorialPageProvider(tutorialPageProvider)
.setOnSkipClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Util.guardarPreferencia(Constantes.VERTUTORIAL_CONTACTO, "ENTENDIDO", getApplicationContext());
try {
//getFragmentManager().popBackStack(); // THIS DON'T CLOSE DE ACTIVITY
finish();
// cierraFragmentTransaction();
} catch (Exception e) {
e.printStackTrace();
}
}
})
.build();
final TutorialFragment tutorialFragment = TutorialFragment.newInstance(tutorialOptions);
getFragmentManager()
.beginTransaction()
.replace(R.id.container, tutorialFragment)
.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
PageFragment Class
class ContactoSecondFragment extends PageFragment {
TextView tv_hola, textView_solicitaremail, textView2, textView1;
public UsuarioDao usuario;
DatabaseManager manager;
public Typeface typeface_bold, typeface_regular;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Context ctx = getContext();
try {
typeface_regular = Typeface.createFromAsset(ctx.getAssets(), Constantes.TYPEFACE_FONT_OPENSANS_REGULAR);
typeface_bold = Typeface.createFromAsset(ctx.getAssets(), Constantes.TYPEFACE_FONT_OPENSANS_SEMIBOLD);
} catch (Exception e) {
e.printStackTrace();
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.contacto_fragment_page_second, container, false);
findViews(view);
try {
if(typeface_bold!=null && typeface_regular!=null) {
tv_hola.setTypeface(typeface_bold);
textView1.setTypeface(typeface_regular);
textView2.setTypeface(typeface_regular);
textView_solicitaremail.setTypeface(typeface_regular);
}
checkDatabaseManager();
UsuarioDao usuario = manager.obtenerUsuario();
String nombre = WordUtils.capitalize(usuario.getNombre().toLowerCase());
tv_hola.setText("Hola " + nombre + "\n ¡Vamos a ayudarte!");
} catch (Exception e) {
tv_hola.setText("Hola ¡Vamos a ayudarte!");
}
return view;
}
private void findViews(View view) {
tv_hola = (TextView) view.findViewById(R.id.textView0_hola);
textView1 = (TextView) view.findViewById(R.id.textView1);
textView2 = (TextView) view.findViewById(R.id.textView2);
textView_solicitaremail = (TextView) view.findViewById(R.id.textView_solicitaremail);
}
#Override
protected int getLayoutResId() {
return R.layout.contacto_fragment_page_second;
}
#NonNull
#Override
protected TransformItem[] getTransformItems() {
return new TransformItem[]{
TransformItem.create(R.id.textView0_hola, Direction.RIGHT_TO_LEFT, 0.2f),
TransformItem.create(R.id.img_hola, Direction.LEFT_TO_RIGHT, 0.6f),
TransformItem.create(R.id.textView1, Direction.RIGHT_TO_LEFT, 0.8f),
TransformItem.create(R.id.textView2, Direction.LEFT_TO_RIGHT, 0.10f),
TransformItem.create(R.id.img_email, Direction.RIGHT_TO_LEFT, 0.3f),
TransformItem.create(R.id.textView_solicitaremail, Direction.LEFT_TO_RIGHT, 0.9f)
};
}
private void checkDatabaseManager() {
try {
if (manager == null) {
DatabaseManager.init(getContext());
manager = DatabaseManager.getInstance();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Error
Attempt to get length of null array
java.lang.NullPointerException: Attempt to get length of null array
at com.cleveroad.slidingtutorial.PageImpl.onDestroyView(PageImpl.java:71)
at com.cleveroad.slidingtutorial.PageFragment.onDestroyView(PageFragment.java:73)
at android.app.Fragment.performDestroyView(Fragment.java:2570)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1061)
at android.app.FragmentManagerImpl.detachFragment(FragmentManager.java:1351)
at android.app.BackStackRecord.run(BackStackRecord.java:798)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1580)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:483)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Related
View Complaint Activity:
In this i have done debugging but i was unable to know the reason why the data is coming twice after scrolling. I have even check the data coming from server through postman but the data is not coming duplicate its coming perfectly fine the problem seems to be in front end while we are putting the data through adapter inside activity on scrolling.
public class ViewComplaintActivity extends AppCompatActivity implements AbsListView.OnScrollListener, View.OnClickListener {
TextView tv_notData;
List<Ticket> _data = new ArrayList<Ticket>();
ComplaintsAdapter settlementAdapter;
private String TAG = "ViewComplaintActivity";
private int visibleThreshold = 5;
private int currentPage = 0;
private int previousTotal = 0;
private boolean loading = true;
private boolean userScrolled = false;
a) Its is a Complaints Activity where we are showing the data comimg from server through adapter.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_compliants);
ButterKnife.bind(this);
try {
settlementAdapter = new ComplaintsAdapter(ViewComplaintActivity.this, _data);
AlphaInAnimationAdapter animationAdapter = new AlphaInAnimationAdapter(settlementAdapter);
animationAdapter.setAbsListView(ll_complaint_list);
ll_complaint_list.setAdapter(animationAdapter);
getComplaints(Utility.getTerminalId(ViewComplaintActivity.this), 0);
ll_complaint_list.setOnScrollListener(this);
fab_raise_complaint.setOnClickListener(this);
fab_call_customer.setOnClickListener(this);
ivBackButton.setOnClickListener(this);
} catch (NullPointerException e) {
Log.e(TAG, e.toString());
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
private void getComplaints(String terminalid, int pagenumber) {
if (!NetworkConnection.isConnected(this)) {
Toast.makeText(this, R.string.no_connection, Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("subIdentifier", terminalid);
jsonObject.addProperty("pageLimit", "10");
jsonObject.addProperty("lastPageIndex", "" + pagenumber);
IRetrofit iRetrofit = MoApplication.getInstance().getRetrofitOsTickets(this).create(IRetrofit.class);
Log.e(TAG,"jsonObject "+jsonObject);
iRetrofit.getAllTicket(jsonObject, new Callback<Response>() {
#Override
public void success(Response response, Response response2) {
progressBar.setVisibility(View.GONE);
try {
if (response.getStatus() == 200) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody().in()));
String resultFromJson = bufferedReader.readLine();
/* Log.e(TAG, "resultFromJson " + resultFromJson);*/
GetTicketsResponse getSettlementsResDTO = new Gson().fromJson(resultFromJson, GetTicketsResponse.class);
switch (getSettlementsResDTO.getResCode()) {
case "0001":
if (null != getSettlementsResDTO.getTickets()) {
_data.addAll(getSettlementsResDTO.getTickets());
settlementAdapter.notifyDataSetChanged();
if (_data.isEmpty()) {
tv_notData.setVisibility(View.VISIBLE);
} else {
tv_notData.setVisibility(View.GONE);
}
} else {
Utility.showToast(ViewComplaintActivity.this, "No data found.");
}
break;
default:
Utility.showToast(ViewComplaintActivity.this, "Please try later.");
break;
}
}
} catch (NullPointerException e) {
Log.e(TAG, "" + e.toString());
} catch (Exception e) {
Log.e(TAG, "" + e.toString());
}
}
#Override
public void failure(RetrofitError error) {
if (Utility.parseException(error)){
Utility.mPosLogoutService((AppCompatActivity) ViewComplaintActivity.this);
}
progressBar.setVisibility(View.GONE);
}
});
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
/*Log.e(TAG,"one");*/
Log.e(TAG,"scrollState "+scrollState);
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
userScrolled = true;
fab_call_customer.hide();
fab_raise_complaint.hide();
} else {
fab_call_customer.show();
fab_raise_complaint.show();
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
/*Log.e(TAG,"two");*/
view.getSelectedItemPosition();
if (userScrolled) {
Log.e(TAG,"loading "+loading);
if (loading) {
Log.e(TAG,"totalItemCount "+totalItemCount);
Log.e(TAG,"previousTotal "+previousTotal);
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
currentPage++;
}
}
Log.e(TAG,"loadin after scroll "+loading);
if (!loading && ((totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold))) {
getComplaints(Utility.getTerminalId(ViewComplaintActivity.this), currentPage);
loading = true;
}
}
else {
Log.e(TAG,"user is idle");
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
public void onClick(View v) {
if (NetworkConnection.isConnected(this)) {
if (v == fab_raise_complaint) {
Utility.navigate(this, RaiseComplaintActivity.class);
} else if (v == fab_call_customer) {
Intent callIntent = new Intent(Intent.ACTION_DIAL);
callIntent.setData(Uri.parse("tel:" + Uri.encode(Constant.helplineNumber.trim())));
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(callIntent);
} else if (v == ivBackButton) {
startActivity(new Intent(ViewComplaintActivity.this, HomeQrActivity.class));
finish();
}
} else {
Toast.makeText(this, R.string.no_connection, Toast.LENGTH_SHORT).show();
}
}
public class ComplaintsAdapter extends BaseAdapter {
private static String TAG = "ComplaintsAdapter";
List<Ticket> _data;
Context _c;
ViewHolder holder;
public ComplaintsAdapter(Context context, List<Ticket> getData) {
_data = getData;
_c = context;
}
#Override
public int getCount() {
Log.e(TAG,"_data.size()"+_data.size());
return _data.size();
}
#Override
public Object getItem(int position) {
Log.e(TAG,"_data.get(position)"+_data.get(position));
return _data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
/*Log.e(TAG,"getData"+_data.toString());*/
try {
if (view == null) {
/*Log.e(TAG,"getData1"+_data.toString());*/
LayoutInflater li = (LayoutInflater)
_c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.row_item_view_complaints,
null);
} else {
/*Log.e(TAG,"getData2"+_data.toString());*/
view = convertView;
}
holder = new ViewHolder();
holder.tv_ticketNo = (TextView)
view.findViewById(R.id.tv_ticketNo);
holder.tv_submitDate = (TextView)
view.findViewById(R.id.tv_submitDate); //ticket comments
holder.tv_updatedDate = (TextView)
view.findViewById(R.id.tv_updatedDate);//will act as ticket
last modified time
holder.tv_ticketStatus = (TextView)
view.findViewById(R.id.tv_ticketStatus); //ticket status open
or close
holder.tv_comment = (TextView)
view.findViewById(R.id.tv_comment);
holder.tv_subject = (TextView)
view.findViewById(R.id.tv_subject);
final Ticket ticket = _data.get(position);
holder.tv_ticketNo.setText("#" + ticket.getTicketNo());
holder.tv_submitDate.setText(Html.fromHtml("<b> Created On:
</b>" + Utility.dateReformatting("yyyy-MM-dd HH:mm:ss", "dd
MMM yyyy", ticket.getCreated())));
holder.tv_updatedDate.setText(Html.fromHtml("<b> Modified On:
</b>" + Utility.dateReformatting("yyyy-MM-dd HH:mm:ss", "dd
MMM yyyy", ticket.getModified())));
holder.tv_ticketStatus.setText(ticket.getStatus());
holder.tv_subject.setText(null != ticket.getSubject() && !ticket.getSubject().isEmpty() ? ticket.getSubject().trim().replace("|", "") : "NA"); //comments
if (null != ticket.getComment() && !ticket.getComment().isEmpty()) {
holder.tv_comment.setText(Html.fromHtml(ticket.getComment()));
holder.tv_comment.setVisibility(View.VISIBLE);
} else {
holder.tv_comment.setVisibility(View.GONE);
}
//holder.tv_comment.setText(null != ticket.getComment() && !ticket.getComment().isEmpty() ? ticket.getComment() : ""); //comments
if (ticket.getStatus().startsWith("Open"))
holder.tv_ticketStatus.setTextColor(_c.getResources().getColor(R.color.green_success));
else
Log.e(TAG,"getData4"+_data.toString());
holder.tv_ticketStatus.setTextColor(_c.getResources().getColor(R.color_color));
} catch (NullPointerException e) {
Log.e(TAG, e.toString());
} catch (Exception e) {
Log.e(TAG, e.toString());
}
return view;
}
public void set_data(List<Ticket> _data) {
this._data = _data;
}
static class ViewHolder {
public TextView tv_ticketStatus, tv_ticketNo, tv_submitDate,
tv_updatedDate, tv_comment, tv_subject;
}
}
My Main Activity has three tabs. Each tab is a fragment. Now if you change the theme (white and dark are available), the activity is being recreated so that the change takes effect. But the app crashes.
How I deal with the fragments:
if (savedInstanceState == null) {
pageadapter = new SectionsPageAdapter(getSupportFragmentManager());
rFragMore = new RoomlistFragmentMore();
rFragMyRooms = new RoomlistFragmentMyRooms();
rFragFavs = new RoomlistFragmentFavorites();
} else {
rFragMyRooms = (RoomlistFragmentMyRooms)pageadapter.getItem(0);
rFragFavs = (RoomlistFragmentFavorites)pageadapter.getItem(1);
rFragMore = (RoomlistFragmentMore)pageadapter.getItem(2);
pageadapter.clearAdapter();
pageadapter = new SectionsPageAdapter(getSupportFragmentManager());
}
How I set up the Adapter:
private void setupViewPager(ViewPager viewPager) {
pageadapter.addFragment(rFragMyRooms, getResources().getString(R.string.myrooms));
pageadapter.addFragment(rFragFavs, getResources().getString(R.string.favorites));
pageadapter.addFragment(rFragMore, getResources().getString(R.string.more));
viewPager.setAdapter(pageadapter);
}
My Adapter:
public class SectionsPageAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
public void clearAdapter() {
mFragmentList.clear();
mFragmentTitleList.clear();
}
public SectionsPageAdapter(FragmentManager fm) {
super(fm);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
}
And the Error Log:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.FileInputStream android.content.Context.openFileInput(java.lang.String)' on a null object reference
at com.yannick.mychatapp.RoomlistFragmentMore.readFromFile(RoomlistFragmentMore.java:246)
at com.yannick.mychatapp.RoomlistFragmentMore.addRoomToList(RoomlistFragmentMore.java:121)
at com.yannick.mychatapp.RoomlistFragmentMore.access$000(RoomlistFragmentMore.java:46)
at com.yannick.mychatapp.RoomlistFragmentMore$1.onDataChange(RoomlistFragmentMore.java:79)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##16.0.4:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##16.0.4:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database##16.0.4:55)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
EDIT: the code of RoomlistFragmentMore
public class RoomlistFragmentMore extends Fragment {
private ListView listView;
private List<HashMap<String, String>> listItems = new ArrayList<>();
private String raumname, theme;
private static String userID = "";
private SimpleAdapter adapter;
private DatabaseReference root = FirebaseDatabase.getInstance().getReference().getRoot().child("rooms");
private ArrayList<Room> raumliste = new ArrayList<>();
private TextView keinraumgefunden;
private String[] kat;
private static final String TAG = "RoomlistFragmentMore";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.roomlist_fragment_more,container,false);
listView = view.findViewById(R.id.listView);
keinraumgefunden = view.findViewById(R.id.keinraumgefunden);
kat = getResources().getStringArray(R.array.categories);
theme = readFromFile("mychatapp_theme.txt");
adapter = new SimpleAdapter(getActivity(), listItems, R.layout.listlayout,
new String[]{"name", "kat", "lock", "newest"},
new int[]{R.id.raumname, R.id.raumkat, R.id.raumlock, R.id.raumdatum});
listView.setAdapter(adapter);
root.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
addRoomToList(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getActivity(), R.string.nodatabaseconnection, Toast.LENGTH_SHORT).show();
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
int position = listView.getPositionForView(view);
String roomname = listItems.get(position).values().toArray()[0].toString();
Room room = findRoom(raumliste, roomname);
request_password(room, position);
}
});
adapter.registerDataSetObserver(new DataSetObserver() {
#Override
public void onChanged() {
if (raumliste.isEmpty()) {
keinraumgefunden.setText(R.string.noroomfound);
} else {
keinraumgefunden.setText("");
}
}
});
return view;
}
private void addRoomToList(DataSnapshot dataSnapshot) {
HashMap<String, String> raeume = new HashMap<>();
raumliste.clear();
for(DataSnapshot uniqueKeySnapshot : dataSnapshot.getChildren()){
String name = uniqueKeySnapshot.getKey();
for(DataSnapshot roomSnapshot : uniqueKeySnapshot.getChildren()){
Room room = roomSnapshot.getValue(Room.class);
room.setRaumname(name);
if (!room.getPasswd().equals(readFromFile("mychatapp_raum_" + name + ".txt"))) {
raeume.put(name, kat[Integer.parseInt(room.getCaty())]+"/"+"\uD83D\uDD12"+"/");
raumliste.add(room);
}
break;
}
}
listItems.clear();
Iterator it = raeume.entrySet().iterator();
while (it.hasNext()){
HashMap<String, String> resultsMap = new HashMap<>();
Map.Entry pair = (Map.Entry)it.next();
resultsMap.put("name", pair.getKey().toString());
String daten = pair.getValue().toString();
String caty = daten.substring(0, daten.indexOf("/"));
String lock = daten.substring(daten.indexOf("/")+1, daten.lastIndexOf("/"));
String time = daten.substring(daten.lastIndexOf("/")+1, daten.length());
String newestTime = "";
int index = 0;
resultsMap.put("kat", caty);
resultsMap.put("lock", lock);
resultsMap.put("newest", newestTime);
if (time.equals("")) {
listItems.add(resultsMap);
} else {
listItems.add(index, resultsMap);
}
}
adapter.notifyDataSetChanged();
}
private void request_password(final Room room, final int position) {
LayoutInflater inflater = LayoutInflater.from(getContext());
View view = inflater.inflate(R.layout.enter_room, null);
raumname = room.getRaumname();
userID = readFromFile("mychatapp_userid.txt");
final EditText input_field = view.findViewById(R.id.room_password);
AlertDialog.Builder builder;
if (theme.equals(getResources().getStringArray(R.array.themes)[1])) {
builder = new AlertDialog.Builder(new ContextThemeWrapper(getActivity(), R.style.AlertDialogDark));
} else {
builder = new AlertDialog.Builder(getActivity());
}
builder.setTitle(R.string.pleaseenterpassword);
builder.setView(view);
builder.setCancelable(false);
builder.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
View view = ((AlertDialog) dialogInterface).getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
dialogInterface.cancel();
}
});
final AlertDialog alert = builder.create();
alert.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
Button b = alert.getButton(AlertDialog.BUTTON_POSITIVE);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (input_field.getText().toString().trim().equals(room.getPasswd())) {
Intent tabIntent = new Intent("tab");
LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(tabIntent);
Intent intent = new Intent(getActivity(), ChatActivity.class);
intent.putExtra("room_name", room.getRaumname());
intent.putExtra("user_id",userID);
updateRoomList(position);
writeToFile(room.getPasswd(),"mychatapp_raum_" + raumname + ".txt");
alert.cancel();
startActivity(intent);
} else {
Toast.makeText(getActivity(), R.string.wrongpassword, Toast.LENGTH_SHORT).show();
}
}
});
}
});
alert.show();
}
public Room findRoom(ArrayList<Room> raumliste, String raumname) {
for (Room room : raumliste) {
if (room.getRaumname().equals(raumname)) {
return room;
}
}
return null;
}
public void writeToFile(String text, String datei) {
Context context = getActivity();
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput(datei, Context.MODE_PRIVATE));
outputStreamWriter.write(text);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
public String readFromFile(String datei) {
Context context = getActivity();
String erg = "";
try {
InputStream inputStream = context.openFileInput(datei);
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
erg = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return erg;
}
private void updateRoomList(int position) {
listItems.remove(position);
adapter.notifyDataSetChanged();
}
}
The NullPointerException occured while onDataChange() was executed (you can see this by reading the stack trace). More specifically, readFromFile() needs a valid Context to open a file.
Since your app crashed we know that getActivity() did return null. How can this happen?
You add the ValueEventListener in onCreateView(). At this point in time, the Fragment has a valid Context (see the documentation for an explanation of the Lifecycle), so all is well for the moment.
But since you do not remove the ValueEventListener, it will continue to fire even if the Fragment is temporarily not attached to the Activity because the user swiped to the next page. The Fragment won't be garbage collected because you keep it in a list and reuse it.
This approach is basically ok if you implement null checks to avoid accessing the Activity, the Context or Views in general while they are not present. Of course, you could consider a stronger separation of the data and the View layer as suggested in this guide to app architecture
i have some problem with my JSON code.
I want to display a list that contain text and image. The text and image stored on my online database, i using JSON for taking them down to my android app.
The JSON doesn't display any error, the text are displayed but the image are not appear.
I check the logcat and there's no error for this process. I using viewAdapter for displaying the image on the list.
Please master help me, can you gimme some simple explanation how to solve this??
Thanks...
NB. This is my code for HomeFragment.java (where i doing the JSON).
public class HomeFragment extends Fragment implements InternetConnectionListener, ApiHandler.ApiHandlerListener {
private static final String ARG_SECTION_NUMBER = "section_number";
private final int CATEGORY_ACTION = 1;
private CategorySelectionCallbacks mCallbacks;
private ArrayList<Category> categoryList;
private ListView categoryListView;
private String Error = null;
private InternetConnectionListener internetConnectionListener;
public HomeFragment() {
}
public static HomeFragment newInstance(int sectionNumber) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((HomeActivity) activity).onSectionAttached(getArguments().getInt(ARG_SECTION_NUMBER));
try {
mCallbacks = (CategorySelectionCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement CategorySelectionCallbacks.");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
categoryListView = (ListView) rootView.findViewById(R.id.categoryListView);
return rootView;
}
#Override
public void onResume() {
super.onResume();
if (UtilMethods.isConnectedToInternet(getActivity())) {
initCategoryList();
} else {
internetConnectionListener = (InternetConnectionListener) HomeFragment.this;
showNoInternetDialog(getActivity(), internetConnectionListener,
getResources().getString(R.string.no_internet),
getResources().getString(R.string.no_internet_text),
getResources().getString(R.string.retry_string),
getResources().getString(R.string.exit_string), CATEGORY_ACTION);
}
}
public class getCategList extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
/**
* json is populating from text file. To make api call use ApiHandler class
*
* <CODE>ApiHandler apiHandler = new ApiHandler(this, URL_GET_CATEGORY);</CODE> <BR>
* <CODE>apiHandler.doApiRequest(ApiHandler.REQUEST_GET);</CODE> <BR>
*
* You will get the response in onSuccessResponse(String tag, String jsonString) method
* if successful api call has done. Do the parsing as the following.
*/
URL hp = null;
try {
hp = new URL(
getString(R.string.liveurl) + "foodcategory.php");
Log.d("URL", "" + hp);
URLConnection hpCon = hp.openConnection();
hpCon.connect();
InputStream input = hpCon.getInputStream();
BufferedReader r = new BufferedReader(new InputStreamReader(input));
String x = "";
x = r.readLine();
String total = "";
while (x != null) {
total += x;
x = r.readLine();
}
Log.d("UR1L", "" + total);
JSONArray j = new JSONArray(total);
Log.d("URL1", "" + j.length());
categoryList = new ArrayList<Category>();
for (int i = 0; i < j.length(); i++) {
Category category = new Category();// buat variabel category
JSONObject Obj;
Obj = j.getJSONObject(i); //sama sperti yang lama, cman ini lebih mempersingkat karena getJSONObject cm d tulis sekali aja disini
category.setId(Obj.getString(JF_ID));
category.setTitle(Obj.getString(JF_TITLE));
category.setIconUrl(Obj.getString(JF_ICON));
if (!TextUtils.isEmpty(Obj.getString(JF_BACKGROUND_IMAGE))) {
category.setImageUrl(Obj.getString(JF_BACKGROUND_IMAGE));
}
Log.d("URL1",""+Obj.getString(JF_TITLE));
categoryList.add(category);
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
categoryListView.setAdapter(new CategoryAdapter(getActivity(), mCallbacks, categoryList));
}
});
}catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Error = e.getMessage();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Error = e.getMessage();
} catch (JSONException e) {
// TODO Auto-generated catch block
Error = e.getMessage();
e.printStackTrace();
} catch (NullPointerException e) {
// TODO: handle exception
Error = e.getMessage();
}
return null;
}
}
//! function for populate category list
private void initCategoryList() {
new getCategList().execute();
}
#Override
public void onConnectionEstablished(int code) {
if (code == CATEGORY_ACTION) {
initCategoryList();
}
}
#Override
public void onUserCanceled(int code) {
if (code == CATEGORY_ACTION) {
getActivity().finish();
}
}
//! catch json response from here
#Override
public void onSuccessResponse(String tag, String jsonString) {
//! do same parsing as done in initCategoryList()
}
//! detect response error here
#Override
public void onFailureResponse(String tag) {
}
//! callback interface listen by HomeActivity to detect user click on category
public static interface CategorySelectionCallbacks {
void onCategorySelected(String catID, String title);
}
}
This code for categoryAdapter.java (where i put the result of JSON to the list)
public class CategoryAdapter extends ArrayAdapter<Category> implements View.OnClickListener {
private final LayoutInflater inflater;
private final ArrayList<Category> categoryList;
private Activity activity;
private HomeFragment.CategorySelectionCallbacks mCallbacks;
private String dummyUrl = "http://www.howiwork.org";
AbsListView.LayoutParams params;
public CategoryAdapter(Activity activity, HomeFragment.CategorySelectionCallbacks mCallbacks, ArrayList<Category> categoryList) {
super(activity, R.layout.layout_category_list);
this.activity = activity;
this.inflater = LayoutInflater.from(activity.getApplicationContext());
this.categoryList = categoryList;
this.mCallbacks = mCallbacks;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder row;
if (convertView == null) {
convertView = inflater.inflate(R.layout.layout_category_list, null);
row = new ViewHolder();
row.bannerImage = (ImageView) convertView.findViewById(R.id.catBannerImageView);
row.categoryImage = (ImageView) convertView.findViewById(R.id.catImageView);
row.categoryName = (TextView) convertView.findViewById(R.id.catNameTV);
} else {
row = (ViewHolder) convertView.getTag();
}
Category category = categoryList.get(position);
Picasso.with(activity).load(UtilMethods
.getDrawableFromFileName(activity,category.getIconUrl()))
.tag(category.getIconUrl())
.into(row.categoryImage);
row.categoryName.setText(category.getTitle());
Picasso.with(activity)
.load(UtilMethods.getDrawableFromFileName(activity,category.getImageUrl()))
.placeholder(R.drawable.img_banner_placeholder)
.tag(category.getIconUrl())
.fit()
.into(row.bannerImage);
row.bannerImage.setOnClickListener(this);
row.categoryImage.setTag(position);
row.categoryName.setTag(position);
row.bannerImage.setTag(position);
return convertView;
}
#Override
public int getCount() {
return categoryList.size();
}
#Override
public void onClick(View v) {
int position = Integer.parseInt(v.getTag().toString());
mCallbacks.onCategorySelected(categoryList.get(position).getId(),
categoryList.get(position).getTitle());
}
private static class ViewHolder {
public ImageView bannerImage;
public TextView categoryName;
public ImageView categoryImage;
}
}
Try this.
Picasso.with(activity).load(category.getIconUrl())
.into(row.categoryImage);
If it worked !. You Check the UtilMethods.getDrawableFromFileName() !!!
So im trying to update a list with the information provided from a server communicated by JSON.
This is the class doing the communication:
package com.example.simon_000.buddy;
public class TCPConnection {
private RunOnThread thread;
private Receive receive;
private MainActivity ma;
private Socket socket;
private DataInputStream input;
private DataOutputStream output;
private InetAddress address;
private int connectionPort;
private String ip;
private Exception exception;
public static String id;
public static ArrayList<members> memberList = new ArrayList<members>();
public static ArrayList<String> groupsList = new ArrayList<String>();
public static ArrayList<String> namesList = new ArrayList<String>();
public TCPConnection(String ip, int connectionPort, MainActivity ma) {
this.ip = ip;
this.connectionPort = connectionPort;
thread = new RunOnThread();
this.ma = ma;
}
public void connect() {
thread.start();
thread.execute(new Connect());
}
public void disconnect() {
thread.execute(new Disconnect());
}
public void send(String expression) {
thread.execute(new Send(expression));
}
private class Receive extends Thread {
public void run() {
String result;
try {
while (receive != null) {
result = (String) input.readUTF();
newMessage(result);
}
} catch (Exception e) { // IOException, ClassNotFoundException
receive = null;
}
}
}
public void newMessage(final String answer) {
ma.runOnUiThread(new Runnable() {
public void run() {
String message = answer;
String type;
JSONObject jObj = null;
try {
Log.d("TEST", message);
jObj = new JSONObject(message);
type = jObj.getString("type");
if (type.equals("groups")) {
recevieGroups(jObj);
}
else if (type.equals("register")) {
recevieID(jObj);
}
else if (type.equals("members")) {
receiveMembers(jObj);
}
else if (type.equals("location")) {
receiveLocations(jObj);
} else if (type.equals("locations")) {
receiveLocations(jObj);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
public void receiveLocations(JSONObject jObj) throws JSONException {
// { ”type”:”locations”, ”group”:”NAME”, ”locations”:[ {”member”:”NAME”, ”longitude”:”LONGITUDE”, ”latitude”:”LATITUDE” }, … ] }
JSONArray jArray = jObj.getJSONArray("locations");
for (int i = 0; i < jArray.length(); i++) {
members m = new members();
JSONObject jRealObject = jArray.getJSONObject(i);
m.setName(jRealObject.getString("member"));
m.setLongitude(Double.parseDouble(jRealObject.getString("longitude")));
m.setLatitude(Double.parseDouble(jRealObject.getString("latitude")));
memberList.add(m);
Log.d("TEST", " memberNAMES : " + m.getName()+" lng: "+ m.getLongitude()+" lat: "+m.getLatitude());
}
ma.updateMapMarkers(memberList);
}
public void receiveMembers(JSONObject jObj) throws JSONException {
// { “type”:”members”, “group”:”NAME”, “members”:[ {“member”:”NAME”},…] }
JSONArray jArray = jObj.getJSONArray("members");
for (int i = 0; i < jArray.length(); i++) {
String n;
JSONObject jRealObject = jArray.getJSONObject(i);
n = jRealObject.getString("member");
Log.d("TEST", " MembernamesBEFORE_ADD : " + n );
namesList.add(n);
Log.d("TEST", " memberNAMES : " + n);
}
}
public void recevieID(JSONObject jObj) throws JSONException {
id = (jObj.getString("id"));
Log.d("TEST", " ID : " + id);
}
public void recevieGroups(JSONObject jObj) throws JSONException {
JSONArray jArray = jObj.getJSONArray("groups");
for (int i = 0; i < jArray.length(); i++) {
String g;
JSONObject jRealObject = jArray.getJSONObject(i);
g = (jRealObject.getString("group"));
groupsList.add(g);
Log.d("TEST", " groupNames : " + g);
}
}
public Exception getException() {
Exception result = exception;
exception = null;
return result;
}
private class Connect implements Runnable {
public void run() {
try {
Log.d("TCPConnection", "Connect-run");
address = InetAddress.getByName(ip);
Log.d("TCPConnection-Connect", "Skapar socket");
socket = new Socket(address, connectionPort);
input = new DataInputStream(socket.getInputStream());
output = new DataOutputStream(socket.getOutputStream());
output.flush();
Log.d("TCPConnection-Connect", "Strömmar klara");
newMessage("CONNECTED");
receive = new Receive();
receive.start();
} catch (Exception e) { // SocketException, UnknownHostException
Log.d("TCPConnection-Connect", e.toString());
exception = e;
newMessage("EXCEPTION");
}
}
}
public class Disconnect implements Runnable {
public void run() {
try {
if (socket != null)
socket.close();
if (input != null)
input.close();
if (output != null)
output.close();
thread.stop();
newMessage("CLOSED");
} catch (IOException e) {
exception = e;
newMessage("EXCEPTION");
}
}
}
public class Send implements Runnable {
private String exp;
public Send(String exp) {
this.exp = exp;
}
public void run() {
try {
output.writeUTF(exp);
output.flush();
} catch (IOException e) {
exception = e;
newMessage("EXCEPTION");
}
}
}
}
This is the "Controller":
package com.example.simon_000.buddy;
public class MainActivity extends Activity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
private myMap tempMapfragment = new myMap();
private Menu menu;
private String inetAddress = "195.178.232.7";
private Integer port = 7117;
private TCPConnection connect;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startNavDrawer();
connect = new TCPConnection(inetAddress, port, this);
connect.connect();
}
public void myPosition(String id, double LONGITUDE, double LATITUDE) {
StringWriter stringWriter = new StringWriter();
JsonWriter writer = new JsonWriter(stringWriter);
try {
writer.beginObject().name("type").value("location").name("id").value(id).name("longitude").value(LONGITUDE).name("latitude").value(LATITUDE).endObject();
} catch (IOException e) {
e.printStackTrace();
}
connect.send(stringWriter.toString());
}
public void getMembers(String group) {
StringWriter stringWriter = new StringWriter();
JsonWriter writer = new JsonWriter(stringWriter);
try {
writer.beginObject().name("type").value("members").name("group").value(group).endObject();
} catch (IOException e) {
e.printStackTrace();
}
connect.send(stringWriter.toString());
}
public void getGroups() {
// Aktuella grupper
// { ”type”:”groups” }
// { “type”:”groups”, ”groups”:[ {”group”:”NAME”}, …] }
StringWriter stringWriter = new StringWriter();
JsonWriter writer = new JsonWriter(stringWriter);
try {
writer.beginObject().name("type").value("groups").endObject();
} catch (IOException e) {
e.printStackTrace();
}
connect.send(stringWriter.toString());
}
public void registerGroup(String groupName, String userName) {
StringWriter stringWriter = new StringWriter();
JsonWriter writer = new JsonWriter(stringWriter);
try {
writer.beginObject().name("type").value("register").name("group").value(groupName).name("member").value(userName).endObject();
} catch (IOException e) {
e.printStackTrace();
}
connect.send(stringWriter.toString());
}
public void updateMapMarkers(ArrayList<members> memberList) {
for(members m: memberList){
tempMapfragment.addMarker(m);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
connect.disconnect();
}
private void startNavDrawer() {
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
communication fragment2 = new communication();
switch (position) {
case 0:
// fragment1
// use fragment transaction and add the fragment to the container
fragmentTransaction.replace(R.id.container, fragment2);
fragmentTransaction.commit();
break;
case 1:
// fragment2
fragmentTransaction.replace(R.id.container, tempMapfragment);
fragmentTransaction.commit();
break;
case 2:
// fragment2
break;
default:
// fragment1
// use fragment transaction and add the fragment to the container
fragmentTransaction.replace(R.id.container, fragment2);
fragmentTransaction.commit();
}
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
this.menu = menu;
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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.
int id = item.getItemId();
//Setting maptype
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
This is the fragment, its in the part where i open a Dialog onclick.
package com.example.simon_000.buddy.Fragments;
public class communication extends Fragment {
private ListView list;
private EditText groupet;
private EditText nameet;
private ListView memberList;
private Button btsend, btUpdate;
private GroupAdapter Groupadapter;
private NameAdapter Nameadapter;
public communication() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_communication, container, false);
getGroupInfo();
initiateVariables(view);
return view;
}
private void initiateVariables(View view) {
list = (ListView) view.findViewById(R.id.grouplistView);
// groupsList = new ArrayList<String>();
// namesList = new ArrayList<String>();
groupet = (EditText) view.findViewById(R.id.etgroupName);
nameet = (EditText) view.findViewById(R.id.etUsername);
btsend = (Button) view.findViewById(R.id.btSend);
btUpdate = (Button) view.findViewById(R.id.btUpdate);
groupet.setText("MadKim");
Groupadapter = new GroupAdapter(getActivity(), R.layout.row, TCPConnection.groupsList);
list.setAdapter(Groupadapter);
list.setOnItemClickListener(new listListener());
btsend.setOnClickListener(new Listener());
btUpdate.setOnClickListener(new ListenerUpdate());
}
public void getGroupInfo(){
((MainActivity)getActivity()).getGroups();
}
private class Listener implements View.OnClickListener {
#Override
public void onClick(View view) {
// sc.startThreadCommunication();
String group = groupet.getText().toString();
String name = nameet.getText().toString();
// sending query to server
if(group.isEmpty() || name.isEmpty() ){
Toast.makeText(getActivity(), "You need to fill in all the fields.", Toast.LENGTH_LONG).show();
}else {
((MainActivity)getActivity()).registerGroup(groupet.getText().toString(), nameet.getText().toString());
getGroupInfo();
Groupadapter.notifyDataSetChanged();
//hides keyboard
nameet.clearFocus();
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(nameet.getWindowToken(), 0);
//show user info
Toast.makeText(getActivity(), "Successfully registered to: "+groupet.getText().toString()+
" with username: "+nameet.getText().toString(), Toast.LENGTH_LONG).show();
groupet.setText("");
nameet.setText("");
}
}
}
private class ListenerUpdate implements View.OnClickListener {
#Override
public void onClick(View view) {
getGroupInfo();
Groupadapter = new GroupAdapter(getActivity(), R.layout.row, TCPConnection.groupsList);
list.setAdapter(Groupadapter);
Groupadapter.notifyDataSetChanged();
}
}
//REVENUES list onClick LISTENER
private class listListener implements AdapterView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// ListView Clicked item index
int itemPosition = position;
Nameadapter.notifyDataSetChanged();
((MainActivity)getActivity()).getMembers(TCPConnection.groupsList.get(itemPosition).toString());
Nameadapter.notifyDataSetChanged();
//open selected finanse and show more information
Dialog d = new Dialog(getActivity());
String title = getResources().getString(R.string.dialogTitle);
d.setTitle(title);
d.setCanceledOnTouchOutside(true);
//inserting xml file in Dialog
LayoutInflater factory = LayoutInflater.from(getActivity());
View infoLayout = factory.inflate(R.layout.dialog, null);
memberList = (ListView) infoLayout.findViewById(R.id.memberList);
Button updatebt = (Button) infoLayout.findViewById(R.id.updateDialogBt);
updatebt.setOnClickListener(new updateDialogListener());
d.setContentView(infoLayout);
Nameadapter = new NameAdapter(getActivity(), R.layout.rownames, TCPConnection.namesList);
memberList.setAdapter(Nameadapter);
Nameadapter.notifyDataSetChanged();
d.show();
}
private class updateDialogListener implements View.OnClickListener {
#Override
public void onClick(View view) {
Nameadapter = new NameAdapter(getActivity(), R.layout.rownames, TCPConnection.namesList);
memberList.setAdapter(Nameadapter);
Nameadapter.notifyDataSetChanged();
}
}
}
}
This is my error:
10-27 17:49:00.168 24903-24903/com.example.simon_000.buddy E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.simon_000.buddy, PID: 24903
java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. Make sure your adapter calls notifyDataSetChanged() when its content changes. [in ListView(2131034141, class android.widget.ListView) with Adapter(class com.example.simon_000.buddy.customs.GroupAdapter)]
at android.widget.ListView.layoutChildren(ListView.java:1555)
at android.widget.AbsListView.onTouchUp(AbsListView.java:3624)
at android.widget.AbsListView.onTouchEvent(AbsListView.java:3436)
at android.view.View.dispatchTouchEvent(View.java:7713)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2210)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1945)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1959)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1959)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1959)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1959)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1959)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1959)
at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216)
at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1959)
at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2329)
at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1568)
at android.app.Activity.dispatchTouchEvent(Activity.java:2458)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:2277)
at android.view.View.dispatchPointerEvent(View.java:7893)
at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:3950)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3829)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3395)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3445)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3414)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3521)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3422)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3578)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3395)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3445)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3414)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3422)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3395)
at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:5535)
at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:5515)
at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:5486)
at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:5615)
at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:185)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:138)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:5146)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.j
Your adapter.notifyDataSetChanged() must be called from the UI thread. At present it's called from a background thread.
So instead of:
adapter.notifyDataSetChanged();
You should write:
yourActivity.runOnUiThread(new Runnable(){
public void run() {
adapter.notifyDataSetChanged();
}
});
When calling the method from a background thread.
This allows the ListView to update properly with the data attached to the adapter that has been changed.
I'm working with fragments and flipview but I'm having some problems with this.
When my app opens the first screen show my feed with the FlipView. When I choose another tab of my fragments the fragment of the feed didn't hide or detach. I debugged many times and the code arrives in the detached line but didn't work.
Here is my code
MainActivity class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FontManager.getInstance().initialize(this, R.xml.fonts);
setContentView(R.layout.activity_main);
mFBSession = new FBSessionsManager();
mActionBar = getActionBar();
fm = getFragmentManager();
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
TabHost.OnTabChangeListener mTabChangeListener = new TabHost.OnTabChangeListener() {
#Override
public void onTabChanged(String tabId) {
ft = fm.beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_ENTER_MASK);
FeedPrincipalList mFeedFragment = (FeedPrincipalList) fm.findFragmentByTag(TAB_TAG_FEED);
EverythingFragmentList mEverythingFragment = (EverythingFragmentList) fm.findFragmentByTag(TAB_TAG_ALL_EVERYTHING);
PaymentFragment mPaymentFragment = (PaymentFragment) fm.findFragmentByTag(TAB_TAG_PAYMENT);
ConsultFragmentList mConsultFragmentList = (ConsultFragmentList) fm.findFragmentByTag(TAB_TAG_M_CONSULT);
ProfileFragmentList mProfileFragmentList = (ProfileFragmentList) fm.findFragmentByTag(TAB_TAG_M_PROFILE);
if (mFeedFragment != null){
ft.detach(mFeedFragment);
// ft.commit();
}
if (mEverythingFragment != null)
ft.detach(mEverythingFragment);
if (mPaymentFragment != null)
ft.detach(mPaymentFragment);
if (mConsultFragmentList != null)
ft.detach(mConsultFragmentList);
if (mProfileFragmentList != null){
ft.detach(mProfileFragmentList);
// ft.commit();
}
if (tabId.equalsIgnoreCase(TAB_TAG_FEED)) {
manageContextualActions(true, false);
if (mFeedFragment == null) {
mFeedFragment = new FeedPrincipalList();
ft.add(R.id.realTabContent, mFeedFragment, TAB_TAG_FEED);
} else {
mFeedFragment = new FeedPrincipalList();
ft.attach(mFeedFragment);
}
}
if (tabId.equalsIgnoreCase(TAB_TAG_ALL_EVERYTHING)) {
manageContextualActions(false, true);
if (mEverythingFragment == null) {
mEverythingFragment = new EverythingFragmentList();
ft.replace(R.id.realTabContent, mEverythingFragment, TAB_TAG_ALL_EVERYTHING);
} else {
ft.attach(mEverythingFragment);
}
}
if (tabId.equalsIgnoreCase(TAB_TAG_PAYMENT)) {
manageContextualActions(false, true);
if (mPaymentFragment == null) {
mPaymentFragment = new PaymentFragment();
ft.replace(R.id.realTabContent, mPaymentFragment, TAB_TAG_PAYMENT);
} else {
ft.attach(mPaymentFragment);
}
}
if (tabId.equalsIgnoreCase(TAB_TAG_M_CONSULT)) {
manageContextualActions(false, true);
if (mConsultFragmentList == null) {
mConsultFragmentList = new ConsultFragmentList();
ft.replace(R.id.realTabContent, mConsultFragmentList, TAB_TAG_M_CONSULT);
} else {
ft.attach(mConsultFragmentList);
}
}
if (tabId.equalsIgnoreCase(TAB_TAG_M_PROFILE)) {
manageContextualActions(false, false);
if (mProfileFragmentList == null) {
mProfileFragmentList = new ProfileFragmentList();
ft.replace(R.id.realTabContent, mProfileFragmentList, TAB_TAG_M_PROFILE);
} else {
mProfileFragmentList = new ProfileFragmentList();
ft.attach(mProfileFragmentList);
}
}
ft.commit();
}
};
mTabHost.setOnTabChangedListener(mTabChangeListener);
createAndConfigureTabs();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
public void setupActionBar(int stringTitleID) {
mActionBar.setDisplayShowCustomEnabled(true);
mActionBar.setDisplayShowTitleEnabled(false);
mActionBar.setDisplayUseLogoEnabled(false);
final LayoutInflater inflater = LayoutInflater.from(this);
final View customTitle = inflater.inflate(R.layout.custom_title, null);
((TextView) customTitle.findViewById(R.id.customTitleActionbar)).setText(getResources().getString(stringTitleID));
mActionBar.setCustomView(customTitle);
}
private void createAndConfigureTabs() {
mTabFeed = mTabHost.newTabSpec(TAB_TAG_FEED);
mTabFeed.setIndicator(null, getResources().getDrawable(R.drawable.custom_btn_feed));
mTabFeed.setContent(new TabContentCreator(this));
mTabHost.addTab(mTabFeed);
mTabAllEverything = mTabHost.newTabSpec(TAB_TAG_ALL_EVERYTHING);
mTabAllEverything.setIndicator(null, getResources().getDrawable(R.drawable.custom_btn_all_everything));
mTabAllEverything.setContent(new TabContentCreator(this));
mTabHost.addTab(mTabAllEverything);
mTabCameraAndPayment = mTabHost.newTabSpec(TAB_TAG_PAYMENT);
mTabCameraAndPayment.setIndicator(null, getResources().getDrawable(R.drawable.btn_camera));
mTabCameraAndPayment.setContent(new TabContentCreator(this));
mTabHost.addTab(mTabCameraAndPayment);
mTabConsult = mTabHost.newTabSpec(TAB_TAG_M_CONSULT);
mTabConsult.setIndicator(null, getResources().getDrawable(R.drawable.custom_btn_consult));
mTabConsult.setContent(new TabContentCreator(this));
mTabHost.addTab(mTabConsult);
mTabMyProfile = mTabHost.newTabSpec(TAB_TAG_M_PROFILE);
mTabMyProfile.setIndicator(null, getResources().getDrawable(R.drawable.custom_btn_profile));
mTabMyProfile.setContent(new TabContentCreator(this));
mTabHost.addTab(mTabMyProfile);
mTabWidget = mTabHost.getTabWidget();
for (int i = 0; i minor 5; i++) {
View v = mTabWidget.getChildAt(i);
v.setBackgroundResource(android.R.drawable.screen_background_light_transparent);
if (i == 4)
v.setPadding(0, 0, 0, 12);
}
}
private class TabContentCreator implements TabHost.TabContentFactory {
private Context mContext;
public TabContentCreator(Context context) {
mContext = context;
}
#Override
public View createTabContent(String tag) {
View v = new View(mContext);
return v;
}
}
FeedFragment class
public class FeedPrincipalList extends android.app.Fragment implements FlipView.OnFlipListener, FlipView.OnOverFlipListener, FlipView.OnClickListener {
private static int timelinePage = 1, mPageCount = 0;
private FlipView mFlipView;
private FeedPrincipalAdapter mAdapter;
private FBSessionsManager fbSessionsManager;
private List mList;
private Context context;
private int posicaoTela;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
context = getActivity().getApplicationContext();
View view = inflater.inflate(R.layout.feed_flipview, container);
((MainFragmentActivity) getActivity()).setupActionBar(R.string.title_fragment_feed);
mFlipView = (FlipView) view.findViewById(R.id.fv_feedFlipView_FlipView);
mFlipView.setOnFlipListener(this);
mFlipView.setOverFlipMode(OverFlipMode.RUBBER_BAND);
mFlipView.setEmptyView(view.findViewById(R.id.empty_view));
mFlipView.setOnOverFlipListener(this);
mFlipView.setOnClickListener(this);
fbSessionsManager = new FBSessionsManager(getActivity());
if (mList == null)
new LoadFeedPrincipalData().execute();
return super.onCreateView(inflater,container,savedInstanceState);
}
#Override
public void onFlippedToPage(FlipView v, int position, long id) {
Log.i("pageflip", "Page: " + position);
posicaoTela = position;
if(position > mFlipView.getPageCount()-3 && mFlipView.getPageCount() {
private UtilWS ws;
private JSONObject toSend;
private JsonArray rsArray;
private JsonParser parser;
public LoadFeedPrincipalData() {
ws = new UtilWS();
toSend = new JSONObject();
parser = new JsonParser();
}
#Override
protected Void doInBackground(Void... params) {
try {
toSend.put("token", fbSessionsManager.getStoredPrivateSession()[0]);
toSend.put("userId", fbSessionsManager.getStoredPrivateSession()[1]);
toSend.put("page", timelinePage);
String[] jsonResult = ws.post(UtilWS.URL_TIMELINE, toSend.toString());
if (jsonResult[0].equals("200")) {
JsonObject temp = parser.parse(jsonResult[1]).getAsJsonObject();
Log.i("JSON",": "+temp.toString());
if (temp.get("success").getAsBoolean()) {
rsArray = temp.get("looks").getAsJsonArray();
if (mPageCount == 0)
mPageCount = temp.get("pageCount").getAsInt();
for (JsonElement el : rsArray) {
if (mList == null)
mList = new ArrayList();
temp = (JsonObject) el;
FeedPrincipalTO tempTudo = new FeedPrincipalTO(temp.get("lookId").getAsString(), temp.get("photoUrl1").getAsString(), temp.get("photoUrl2").getAsString(), temp.get("jaVotou").getAsBoolean(),temp.get("photoVoted").getAsInt() ,temp.get("photo1Total").getAsString(), temp.get("photo2Total").getAsString());
mList.add(tempTudo);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
if (mList != null) {
Log.i("mList","mLista");
mAdapter = new FeedPrincipalAdapter(context,mList);
mAdapter.setCallback(new FeedPrincipalAdapter.Callback() {
#Override
public void onPageRequested(int page) {
mFlipView.smoothFlipTo(page);
}
#Override
public void voteUp(int position) {
Log.i("TESTE","position = " + posicaoTela);
mAdapter.getView(position, null, null).postInvalidate();
// mAdapter.notifyDataSetChanged();
}
});
if (timelinePage == 1) {
mFlipView.setAdapter(mAdapter);
// initListenerList();
} else {
((FeedPrincipalAdapter) mFlipView.getAdapter()).updateList(mList);
((FeedPrincipalAdapter) mFlipView.getAdapter()).notifyDataSetChanged();
}
} else {
mFlipView.setAdapter(new FeedPrincipalAdapter(context,null));
}
}
// private void initListenerList() {
// getListView().setOnScrollListener(new AbsListView.OnScrollListener() {
// #Override
// public void onScrollStateChanged(AbsListView view, int scrollState) {
//
// }
//
// #Override
// public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
// if (firstVisibleItem + visibleItemCount == totalItemCount && totalItemCount != 0) {
// if (timelinePage minor mPageCount) {
// timelinePage++;
// new LoadFeedPrincipalData().execute();
// }
// }
// }
// });
// }
}
}
Please, help me with this!!!
I'm using the FlipView https://github.com/emilsjolander/android-FlipView
Thanks!!!
Finally I solved this problem.
First I changed my Main Class a little.
I changed this two ifs (this fragments uses FlipView) in the MainActivity class.
if (tabId.equalsIgnoreCase(TAB_TAG_FEED)) {
manageContextualActions(true, false);
if (mFeedFragment == null) {
mFeedFragment = new FeedPrincipalList();
ft.add(R.id.realTabContent, mFeedFragment, TAB_TAG_FEED);
} else {
// mFeedFragment = new FeedPrincipalList();
ft.attach(mFeedFragment);
}
}
if (tabId.equalsIgnoreCase(TAB_TAG_M_PROFILE)) {
manageContextualActions(false, false);
if (mProfileFragmentList == null) {
mProfileFragmentList = new ProfileFragmentList();
ft.add(R.id.realTabContent, mProfileFragmentList, TAB_TAG_M_PROFILE);
} else {
// mProfileFragmentList = new ProfileFragmentList();
ft.attach(mProfileFragmentList);
}
}
Second I changed my method onCreateView of my FeedFragment class.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
context = getActivity().getApplicationContext();
((MainFragmentActivity) getActivity()).setupActionBar(R.string.title_fragment_feed);
fbSessionsManager = new FBSessionsManager(getActivity());
if (mList == null){
view = inflater.inflate(R.layout.feed_flipview, container,true);
mFlipView = (FlipView) view.findViewById(R.id.fv_feedFlipView_FlipView);
mFlipView.setOnFlipListener(this);
mFlipView.setOverFlipMode(OverFlipMode.RUBBER_BAND);
mFlipView.setEmptyView(view.findViewById(R.id.empty_view));
mFlipView.setOnOverFlipListener(this);
new LoadFeedPrincipalData().execute();
}
return super.onCreateView(inflater,container,savedInstanceState);
}
You can see the difference. I only inflate the view in the first time. After this my mList(it's a List of MyGetSetClass) it's not null anymore.
And to finish I Override this two methods on my FeedFragment class.
#Override
public void onDetach() {
super.onDetach();
// Log.i("onDetach", "FeedPrincipalList");
mList = null;
timelinePage = 1;
mPageCount = 0;
}
#Override
public void onStart() {
super.onStart();
// Log.i("onStart", "FeedPrincipalList");
this.mFlipView.setVisibility(View.VISIBLE);
}
#Override
public void onStop() {
super.onStop();
// Log.i("onStop","FeedPrincipalList");
this.mFlipView.setVisibility(View.INVISIBLE);
}
In the detach method I clean all my static variables that I will use when I start the app again.
The onStart and the onStop I use to change the Visibility of my FlipView.
That's it.
I hope this help everyone!!!