I am learning to program for android and java in general and need some help with the "Navigation Drawer" on android.
I am struggling to add a switch statement to the click listener for the drawer items, The code I am using is taken from an example here: http://hmkcode.com/android-creating-a-navigation-drawer/
How exactly should I handle the switch statement so as to launch new activities from the touch of one of the items?
Thank you
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
actionBarDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Call ActionBarDrawerToggle.onOptionsItemSelected(), if it returns true
// then it has handled the app icon touch event
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, ((TextView)view).getText(), Toast.LENGTH_LONG).show();
drawerLayout.closeDrawer(drawerListView);
}
}
Edit....
public void onItemClick(AdapterView parent, View view, int position, long id) {
switch (position){
case 0:
new DataTask(this).execute();
MainActivity.this.finish();//Set this Activity to Finish so no loop back
Intent intent=new Intent(MainActivity.this,SplashScreen.class);
startActivity(intent);
System.out.println("Click working");
case 1:
//do stuff
default:
break;
}
The new DataTask(this).execute(); is giving this warning....The constructor DataTask(MainActivity.DrawerItemClickListener) is undefined. I am unsure why?
DataTask Class...
public class DataTask extends AsyncTask<Void, Void, Integer> {
Context context;
DataTask(Context context) {
this.context = context.getApplicationContext();
}
// Global Int for counting how many Tasks have been completed
int asynCount = 0;
ArrayList<String> arr_dataVts=new ArrayList<String>();
ArrayList<String> arr_dataNtm=new ArrayList<String>();
ArrayList<String> arr_dataOdas=new ArrayList<String>();
ArrayList<String> arr_dataMetAll=new ArrayList<String>();
ArrayList<String> arr_dataMet3HrTask=new ArrayList<String>();
ArrayList<String> arr_dataTideTask=new ArrayList<String>();
#Override
protected Integer doInBackground(Void... params) {
//VtsAsyncTask
VtsTask task1 = new VtsTask();
task1.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
//NtmAsyncTask
NtmTask task2 = new NtmTask();
task2.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
//OdasAsyncTask
OdasTask task3 = new OdasTask();
task3.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
//MetAllTask
MetAllTask task4 = new MetAllTask();
task4.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
//Met3HrTask
Met3HrTask task5 = new Met3HrTask();
task5.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
//TideTask
TideTask task6 = new TideTask();
task6.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
return 1;
}
private class VtsTask extends AsyncTask<Void, Void, ArrayList<String>> {
#Override
protected ArrayList<String> doInBackground(Void... params) {
Document docVTS;
try {
Connection.Response response = Jsoup.connect("https://vts.mhpa.co.uk/main_movelistb.asp")
.timeout(10000)
.ignoreHttpErrors(true)
.execute();
int statusCode = response.statusCode();
if(statusCode == 200) {
docVTS = Jsoup.connect("https://vts.mhpa.co.uk/main_movelistb.asp").timeout(10000).get();
Elements tableRows = docVTS.select("table.dynlist td:eq(0),td:eq(1),td:eq(3),td:eq(4),td:eq(7),td:eq(8)");
tableRows.size();
for(int i = 1; i < 80; i++){// Only allows x results from VTS list, from 1 not 0. 0 produces needless results
String shippingList = tableRows.get(i).text() +"\n";//new line
arr_dataVts.add(shippingList);// Add value to ArrayList
};
} else {
//If can't connect for what ever reason
System.out.println("Received error code for VTS list Data : " + statusCode + " Adding Null values");
for(int i = 1; i < 80; i++){
arr_dataVts.add("No Data" + i);
}
}
}
catch (IOException e) {
e.printStackTrace();
System.out.println("Received timeout error code for VTS list Data : Adding Null values ");
for(int i = 1; i < 80; i++){
arr_dataVts.add("No Data" + i);
}
}
return arr_dataVts;
}
#Override
protected void onPostExecute(ArrayList<String> Param) {
asynCount++;
System.out.println("Vts list Captured" + arr_dataVts + " asynCount= " + asynCount);
if (asynCount == 6){
//Start intents for main activity
System.out.println("asynCount has reached= " + asynCount + " so now starting MainActivity");
Intent intent = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putStringArrayListExtra("data1", arr_dataVts);
intent.putStringArrayListExtra("data2", arr_dataNtm);
intent.putStringArrayListExtra("data3", arr_dataOdas);
intent.putStringArrayListExtra("data4", arr_dataMetAll);
intent.putStringArrayListExtra("data5", arr_dataMet3HrTask);
intent.putStringArrayListExtra("data6", arr_dataTideTask);
context.startActivity(intent);
}else{
//update dialogue
}
}
}
private class NtmTask extends AsyncTask<Void, Void, ArrayList<String>> {
#Override
protected ArrayList<String> doInBackground(Void... params) {
Document docNTM;
try {
Connection.Response response = Jsoup.connect("http://www.milfordfishdocks.com/notices-to-mariners/")
.timeout(10000)
.ignoreHttpErrors(true)
.execute();
int statusCode = response.statusCode();
if(statusCode == 200) {
docNTM = Jsoup.connect("http://www.milfordfishdocks.com/notices-to-mariners/").timeout(10000).get();
Elements elements = docNTM.select("div.news-item-left");
int NtmAmount = elements.size();
String NtmAmt = Integer.toString(NtmAmount);//convert the Int to a string for adding into array
arr_dataNtm.add(NtmAmt);
} else {
System.out.println("Received error code for NTM Data : " + statusCode + " Adding Null values");
arr_dataNtm.add("0");
}
}
catch (IOException e) {
e.printStackTrace();
System.out.println("Received timeout error code for NTM Data : Adding Null values ");
arr_dataNtm.add("0");
}
return arr_dataNtm;
}
#Override
protected void onPostExecute(ArrayList<String> Param) {
asynCount++;
System.out.println("Ntm list Captured" + arr_dataNtm + " asynCount= " + asynCount);
if (asynCount == 6){
//Start intents for main activity
System.out.println("asynCount has reached= " + asynCount + " so now starting MainActivity");
Intent intent = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putStringArrayListExtra("data1", arr_dataVts);
intent.putStringArrayListExtra("data2", arr_dataNtm);
intent.putStringArrayListExtra("data3", arr_dataOdas);
intent.putStringArrayListExtra("data4", arr_dataMetAll);
intent.putStringArrayListExtra("data5", arr_dataMet3HrTask);
intent.putStringArrayListExtra("data6", arr_dataTideTask);
context.startActivity(intent);
}else{
//update dialogue
}
}
}
#Override
protected void onPostExecute(Integer result) {
System.out.println("Data Task Has Executed");
}
}
It can be done like this:
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
switch (position){
case 0:
//do stuff
case 1:
//do stuff
default:
break;
}
drawerListView.setItemChecked(position, true);
drawerListView.setSelection(position);
drawerLayout.closeDrawer(drawerListView);
}
}
Then just attach this listener to your NavList:
drawerListView.setOnItemClickListener(new DrawerItemClickListener());
BTW, you would recommend you to switch fragments instead of switching activities, "Creating a Navigation Drawer" tutorial explains how to work with them
EDIT Handling case 0, replace with following:
new DataTask(MainActivity.this).execute();
Intent intent=new Intent(MainActivity.this,SplashScreen.class);
startActivity(intent);
Log.d("Click working");
MainActivity.this.finish();//Set this Activity to Finish so no loop back
Switch=
(Switch)navigationView.getMenu().findItem(R.id.vibrate).getActionView();
s.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean
isChecked){
if(isChecked)
//do whatever you want to do
}
});
this should work
Related
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 created RecycleView in Fragment as follows:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_new_shop, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
stackView = (RelativeLayout) view.findViewById(R.id.stack_view);
firstStack = (CustomImageView) view.findViewById(R.id.firstStack);
secondStack = (CustomImageView) view.findViewById(R.id.secondStack);
thirdStack = (CustomImageView) view.findViewById(R.id.thirdStack);
stackTopGap = view.findViewById(R.id.view);
new Handler().post(new Runnable() {
#Override
public void run() {
firstStack.getLayoutParams().width = stackView.getWidth() - 40;
secondStack.getLayoutParams().width = stackView.getWidth() - 80;
thirdStack.getLayoutParams().width = stackView.getWidth() - 120;
width = thirdStack.getLayoutParams().width;
recyclerView.getLayoutParams().height = recyclerView.getHeight() - (firstStack.getHeight() + stackTopGap.getHeight());
stackView.getLayoutParams().height = firstStack.getHeight();
}
});
recyclerView.setHasFixedSize(true);
linearLayoutManager=new LinearLayoutManager(getActivity()) {
#Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
// A good idea would be to create this instance in some initialization method, and just set the target position in this method.
LinearSmoothScroller smoothScroller = new LinearSmoothScroller(getContext()) {
#Override
public PointF computeScrollVectorForPosition(int targetPosition) {
//int yDelta = calculateCurrentDistanceToPosition(targetPosition);
return new PointF(0, 200);
}
// This is the important method. This code will return the amount of time it takes to scroll 1 pixel.
// This code will request X milliseconds for every Y DP units.
#Override
protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
return 7 / TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 7, displayMetrics);
}
};
smoothScroller.setTargetPosition(position);
startSmoothScroll(smoothScroller);
}
};
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
#Override
public void onScrolled(final RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
final int positionView = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastVisibleItemPosition();
if (dy > 0) {
if (positionView >= 2) {
final View view = recyclerView.getChildAt(2);
if (view != null && recyclerView.getChildAdapterPosition(view) == positionView) {
TranslateAnimation translateAnimation = new TranslateAnimation(0, 0, 200, 0);
translateAnimation.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
if (counter == 0) {
if (recyclerView.getAdapter().getItemCount() - 4 >= positionView) {
createStackImageView();
}
if (stackView.getChildAt(1) != null) {
//stackView.getChildAt(1).setScaleX(1.5f);
}
counter++;
}
recyclerView.smoothScrollToPosition(positionView);
}
#Override
public void onAnimationEnd(Animation animation) {
view.clearAnimation();
stackView.requestLayout();
stackView.removeView(stackView.getChildAt(1));
stackView.invalidate();
try {
for (int i = 1; i < 4; i++) {
Glide.with(getActivity())
.load(JSONUrl.IMAGE_BASE_URL + imageList.get(positionView + i))
.into((ImageView) stackView.getChildAt(i));
}
} catch (IndexOutOfBoundsException | NullPointerException | IllegalArgumentException ex) {
ex.printStackTrace();
}
counter = 0;
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
translateAnimation.setDuration(150);
view.setAnimation(translateAnimation);
}
}
for (int i = stackView.getChildCount() - 1; i >= 2; i--) {
ResizeAnimation resizeAnimation = new ResizeAnimation(stackView.getChildAt(i));
resizeAnimation.setHeights(stackView.getChildAt(i).getHeight(), stackView.getChildAt(i - 1).getHeight());
resizeAnimation.setWidths(stackView.getChildAt(i).getWidth(), stackView.getChildAt(i - 1).getWidth());
resizeAnimation.setDuration(200);
stackView.getChildAt(i).startAnimation(resizeAnimation);
}
} else if (dy < 0) {
final int position = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastVisibleItemPosition();
if (position == imageList.size() - 1) {
stackView.removeView(firstStack);
stackView.addView(firstStack);
stackView.invalidate();
stackView.requestLayout();
stackView.getChildAt(1).setVisibility(View.VISIBLE);
Glide.with(getActivity())
.load(JSONUrl.IMAGE_BASE_URL + imageList.get(imageList.size() - 1))
.into((ImageView) stackView.getChildAt(1));
} else if (position == imageList.size() - 2) {
stackView.removeView(secondStack);
stackView.addView(secondStack);
secondStack.getLayoutParams().height = firstStack.getHeight() - 20;
secondStack.getLayoutParams().width = firstStack.getWidth() - 40;
stackView.invalidate();
stackView.requestLayout();
stackView.getChildAt(2).setVisibility(View.VISIBLE);
Glide.with(getActivity())
.load(JSONUrl.IMAGE_BASE_URL + imageList.get(imageList.size() - 2))
.into((ImageView) stackView.getChildAt(2));
} else if (position == imageList.size() - 3) {
stackView.removeView(thirdStack);
stackView.addView(thirdStack);
thirdStack.getLayoutParams().height = secondStack.getHeight() - 20;
thirdStack.getLayoutParams().width = secondStack.getWidth() - 40;
stackView.invalidate();
stackView.requestLayout();
stackView.getChildAt(3).setVisibility(View.VISIBLE);
Glide.with(getActivity())
.load(JSONUrl.IMAGE_BASE_URL + imageList.get(imageList.size() - 3))
.into((ImageView) stackView.getChildAt(3));
} else {
stackView.removeView(firstStack);
stackView.addView(firstStack);
stackView.invalidate();
stackView.requestLayout();
}
}
}
});
return view;
}
//In validateToken method data is taken from the json and set to adapter as follows.
private void validateToken() {
final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
if (new ConnectionManager(getActivity()).isConnectedToInternet()) {
final SweetAlertDialog pDialog = new AlertDIalogMessage().showProgressDialog(getActivity(), "Loading...");
if (sharedPreferences.getString(SharedPrefrenceInfo.IS_TOKEN_VALID, "token_invalid").equals("token_invalid")) {
Utils.setTokenInfo(getActivity(), pDialog, new AccessTokenInfoHolder() {
#Override
public void setAcessTokenInfo(String accessToken, String expires_in, String token_type) {
Log.e("Access Token", accessToken);
new ShopFragmentJson(getActivity()).getShopPageContent(pDialog, sharedPreferences.getString(SharedPrefrenceInfo.TOKEN_TYPE, "") + " " + sharedPreferences.getString(SharedPrefrenceInfo.IS_TOKEN_VALID, ""), new ShopPageContentHolder() {
#Override
public void setErrorShopPageContent(String statusCode, String statusText) {
//do nothing here since the case unauthorized will not arrive for the first time
}
#Override
public void setSuccessShopPageContent(String success, String data) {
if (success.equals("true")) {
shoppageInfoList = getShopPageContent(data);
//set the adapter after loading data from url
final NewShopFragmentAdapter recyclerViewAdapter = new NewShopFragmentAdapter(getActivity(), recyclerView.getHeight(), shoppageInfoList);
recyclerView.setAdapter(recyclerViewAdapter);
pDialog.dismiss();
} else {
pDialog.dismiss();
new AlertDIalogMessage().showErrorDialog(getActivity(), data);
}
}
});
}
});
} else {
new ShopFragmentJson(getActivity()).getShopPageContent(pDialog, sharedPreferences.getString(SharedPrefrenceInfo.TOKEN_TYPE, "") + " " + sharedPreferences.getString(SharedPrefrenceInfo.IS_TOKEN_VALID, ""), new ShopPageContentHolder() {
#Override
public void setErrorShopPageContent(String statusCode, String statusText) {
//this method is invoked when unauthorized response come from server
Utils.setTokenInfo(getActivity(), pDialog, new AccessTokenInfoHolder() {
#Override
public void setAcessTokenInfo(String accessToken, String expires_in, String token_type) {
new ShopFragmentJson(getActivity()).getShopPageContent(pDialog, sharedPreferences.getString(SharedPrefrenceInfo.TOKEN_TYPE, "") + " " + sharedPreferences.getString(SharedPrefrenceInfo.IS_TOKEN_VALID, ""), new ShopPageContentHolder() {
#Override
public void setErrorShopPageContent(String statusCode, String statusText) {
//do nothing here since the case unauthorized will not arrive for the first time
}
#Override
public void setSuccessShopPageContent(String success, String data) {
if (success.equals("true")) {
List<ShoppageInfo> shoppageInfoList = getShopPageContent(data);
final NewShopFragmentAdapter recyclerViewAdapter = new NewShopFragmentAdapter(getActivity(), recyclerView.getHeight(), shoppageInfoList);
recyclerView.setAdapter(recyclerViewAdapter);
pDialog.dismiss();
} else {
pDialog.dismiss();
new AlertDIalogMessage().showErrorDialog(getActivity(), data);
}
}
});
}
});
}
#Override
public void setSuccessShopPageContent(String success, String data) {
if (success.equals("true")) {
List<ShoppageInfo> shoppageInfoList = getShopPageContent(data);
//set the adapter after loading data from url
final NewShopFragmentAdapter recyclerViewAdapter = new NewShopFragmentAdapter(getActivity(), recyclerView.getHeight(), shoppageInfoList);
recyclerView.setAdapter(recyclerViewAdapter);
pDialog.dismiss();
} else {
pDialog.dismiss();
new AlertDIalogMessage().showErrorDialog(getActivity(), data);
}
}
});
}
} else {
new SweetAlertDialog(getActivity(), SweetAlertDialog.ERROR_TYPE)
.setTitleText("Oops...")
.setContentText("No internet connection!")
.show();
}
}
No in onResume method i called validate token as follows:
#Override
public void onResume() {
super.onResume();
validateToken();
}
//Now when I call some activity from this fragment and come back with back pressed validate method is called and RecyclerView adapter is reloaded. Now what I want is to maintain the state of RecyclerView such that when I came back from activity RecyclerView stays in the scroll position from when activity is called. But problem for me is it always come from the start. I also see some Stack Overflow post and they suggest me to use Parceable but i don't get any benefit. Is is doing nothing.
Can try this.
You need to maintain an identifier for each row. Then save the first visible row's identifier before you go to the activity. Then when you come back you select that particular row again.
So, I am creating a little trivia game for learning purposes, but I ran into a problem.
First, I had a specific Android Fragment obtaining the data from JSON, and I will simply use that data on the callback method and display it on TextViews and Buttons. Everything was working fine, however, every time I returned to that fragment, the same questions would be there. So I decided to handle that in a better way outside of the callback method.
The problem here is that apparently my Arrays are either null or their lengths is zero. Which is weird, because according to my LOG, data is being passed to those arrays on the callback method.
Here's my full fragment code. Thanks!
public class GameFragment extends Fragment {
private TextView txtQuestion;
private Button btnAnswer1;
private Button btnAnswer2;
private Button btnAnswer3;
private Button btnAnswer4;
private Questions[] gameQuestions;
private Questions[] animeQuestions;
private Questions[] techQuestions;
private Questions[] movieQuestions;
private Questions[][] gameCategories = new Questions[4][];
int correctAnswer = -1;
private TransparentProgressDialog progressBar;
private Handler handler;
private Runnable runnable;
Callback cb = new Callback<MyApiData>(){
#Override
public void success(MyApiData myApiData, Response response) {
gameCategories[0] = new Questions[myApiData.getCategory()[0].getQuestions(0).length];
gameCategories[1] = new Questions[myApiData.getCategory()[1].getQuestions(1).length];
gameCategories[2] = new Questions[myApiData.getCategory()[2].getQuestions(2).length];
gameCategories[3] = new Questions[myApiData.getCategory()[3].getQuestions(3).length];
//gameCategories = new Questions[][] {gameQuestions, animeQuestions, techQuestions, movieQuestions};
for(int i = 0; i < 4 ; i++){
for(int j = 0; j < gameCategories[i].length ; j++){
gameCategories[i][j] = myApiData.getCategory()[i].getQuestions(i)[j];
//Log.d("GameFragment", "gameCategories[i][j] - gameCategories["+i+"]["+j+"]: " + gameCategories[i][j].getQuestion());
}
}
//displayQuestion();
progressBar.dismiss();
displayQuestion();
}
#Override
public void failure(RetrofitError error) {
Log.d("GameScreen", "Callback failed!");
}
};
public GameFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_game, container, false);
txtQuestion = (TextView) view.findViewById(R.id.txtQuestion);
btnAnswer1 = (Button) view.findViewById(R.id.btnAnswer1);
btnAnswer2 = (Button) view.findViewById(R.id.btnAnswer2);
btnAnswer3 = (Button) view.findViewById(R.id.btnAnswer3);
btnAnswer4 = (Button) view.findViewById(R.id.btnAnswer4);
btnAnswer1.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) { checkAnswer(view); } });
btnAnswer2.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) { checkAnswer(view); } });
btnAnswer3.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) { checkAnswer(view); } });
btnAnswer4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkAnswer(view);
}
});
handler = new Handler();
progressBar = new TransparentProgressDialog(getActivity(), R.drawable.loading_spinner);
runnable = new Runnable() {
#Override
public void run() {
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
};
//launchRingDialog();
//RestClient.get().getQuestions(cb);
// Inflate the layout for this fragment
return view;
}
public void launchRingDialog() {
new Thread(new Runnable() {
public void run(){
try {
Log.d("Thred", "Try");
progressBar.show();
RestClient.get().getQuestions(cb);
//Thread.sleep(10000);
} catch (Exception e) {
}
//progressBar.dismiss();
}
}).start();
}
public void checkAnswer(View v){
switch(v.getId()){
case R.id.btnAnswer1:
if(correctAnswer == 1){
feedback(true, btnAnswer1);
}else {
feedback(false, btnAnswer1);
}
break;
case R.id.btnAnswer2:
if(correctAnswer == 2){
feedback(true, btnAnswer2);
}else {
feedback(false, btnAnswer2);
}
break;
case R.id.btnAnswer3:
if(correctAnswer == 3){
feedback(true, btnAnswer3);
}else {
feedback(false, btnAnswer3);
}
break;
case R.id.btnAnswer4:
if(correctAnswer == 4){
feedback(true, btnAnswer4);
}else {
feedback(false, btnAnswer4);
}
break;
default: txtQuestion.setText("Error");
break;
}
}
public void feedback(Boolean correct, Button btn){
if(correct){
btn.setBackgroundColor(Color.GREEN);
btn.setText("CORRECT!");
}else{
btn.setBackgroundColor(Color.RED);
btn.setText("WRONG!");
}
}
#Override
public void onResume() {
super.onResume();
//displayQuestion();
}
public void displayQuestion(){
Random randomizer = new Random();
int randomQuestion;
int category = GTMain.choosenCategory;
if(category == 5){
category = randomizer.nextInt(4);
}
randomQuestion = randomizer.nextInt(25);
Log.d("displayQuestion", "Before if statements");
if(gameCategories != null && gameCategories.length != 0) {
Log.d("displayQuestion", "First if");
if(gameCategories[category] != null && gameCategories[category].length != 0){
Log.d("displayQuestion", "Second if");
txtQuestion.setText(gameCategories[category][randomQuestion].getQuestion());
correctAnswer = gameCategories[category][randomQuestion].getCorrectAnswer();
Log.d("displayQuestion()", "correctAnswer: " + correctAnswer);
btnAnswer1.setText(gameCategories[category][randomQuestion].getAnswers().getA1());
btnAnswer2.setText(gameCategories[category][randomQuestion].getAnswers().getA2());
btnAnswer3.setText(gameCategories[category][randomQuestion].getAnswers().getA3());
btnAnswer4.setText(gameCategories[category][randomQuestion].getAnswers().getA4());
}
}
}
}
PS: On my main activity, I check to see which fragment should be loaded. If it's the fragment that contains the components to display the questions and answer (the one from the code above), I call the following method: gameFragment.launchRingDialog(); (and yes, I have created an instance of my GameFragment fragment before calling that method!)
When onResume() is called, your RestClient.get().getQuestions(cb) is still running in background, and your call displayQuestion(), so of course nothing is shown.
Can you put displayQuestion() inside success() of your callback?
Callback cb = new Callback<MyApiData>(){
#Override
public void success(MyApiData myApiData, Response response) {
....
for(int i = 0; i < 4 ; i++){
for(int j = 0; j < gameCategories[i].length ; j++){
...
}
}
displayQuestion();
}
....
};
I would also suggest you to remove displayQuestion() in onResume() method.
Hey guys i have got this problem for a while now and i cannot figure out as to why it is not working. when i use the code provided by the tutorial that i have followed on YouTube it works fine, which is posting that data as soon as the application starts. However what i am trying to do is post the data as soon as the "Save Register" button is pressed in the menu but the it doesnt work and returns the message as shown in Log Cat.
I am getting the feeling that i am supposed to create an Async task for this however because my android programming is very limited i am not to sure how i would go about creating this.
My Main activity Class:
public class MainActivity extends Activity{
boolean wasApEnabled = false;
static AccessPoint wifiAP;
private WifiManager wifi;
static Button apButton;
static TextView textView;
final String myTag = "DocsUpload";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
apButton = (Button) findViewById(R.id.toggleBtn);
textView = (TextView) findViewById(R.id.wifiClients);
apButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
wifiAP.toggleWifiAP(wifi, MainActivity.this);
}
});
/*Log.i(myTag, "OnCreate()");
Thread t = new Thread(new Runnable() {
#Override
public void run() {
postData();
}
});*/
//t.start();
wifiAP = new AccessPoint(this);
wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
postData();
scan();
//getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD|WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON|WindowManager.LayoutParams.FLAG_DIM_BEHIND);
}
private void scan(){
wifiAP.getClientList(false, new FinishScanListener() {
#Override
public void onFinishScan(final ArrayList<ClientScanResult> clients) {
textView.setText("WifiApState:" + wifiAP.getWifiApState()+ "\n\n");
textView.append("Clients: \n");
for (ClientScanResult clientScanResult : clients){
textView.append("====================\n");
textView.append("ipAddress: " + clientScanResult.getIpAddress() + "\n");
textView.append("Device: " + clientScanResult.getDevice() + "\n");
textView.append("macAddress: " + clientScanResult.getMacAddress() + "\n");
textView.append("isReachable: " + clientScanResult.isReachable() + "\n");
}
}
});
}
public void postData() {
String fullUrl = "https://docs.google.com/forms/d/1yipuuXd5V53Ol12U24Cl2H4RIdYtm622jIk13Zo26cM/formResponse";
HttpRequest mReq = new HttpRequest();
String col1 = "Hello";
String col2 = "World";
String data = "entry_272641491=" + URLEncoder.encode(col1) + "&" +
"entry_130393492=" + URLEncoder.encode(col2);
String response =mReq.sendPost(fullUrl, data);
// Log.i(myTag, response);
}
#Override
public void onResume() {
super.onResume();
if (wasApEnabled) {
if (wifiAP.getWifiApState() != wifiAP.WIFI_STATE_ENABLED && wifiAP.getWifiApState() != wifiAP.WIFI_STATE_ENABLING) {
wifiAP.toggleWifiAP(wifi, MainActivity.this);
}
}
updateStatusDisplay();
}
#Override
public void onPause() {
super.onPause();
boolean wifiApIsOn = wifiAP.getWifiApState()==wifiAP.WIFI_STATE_ENABLED || wifiAP.getWifiApState()==wifiAP.WIFI_STATE_ENABLING;
if (wifiApIsOn){
wasApEnabled = true;
wifiAP.toggleWifiAP(wifi, MainActivity.this);
}else {
wasApEnabled = false;
}
updateStatusDisplay();
}
public static void updateStatusDisplay(){
if (wifiAP.getWifiApState()==wifiAP.WIFI_STATE_ENABLED || wifiAP.getWifiApState()==wifiAP.WIFI_STATE_ENABLING){
apButton.setText("Turn Off");
}else {
apButton.setText("Turn on");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0,0,0, "Get Clients");
menu.add(0,1,0, "Save Register");
getMenuInflater().inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()){
case 0:
scan();
break;
case 1:
postData();
break;
}
return super.onMenuItemSelected(featureId, item);
}
}
This is the helper class that i have used, Credit goes to this stack overflow user for creating this class
Secure HTTP Post in Android
This is the log cat that i am getting
03-12 15:06:27.428 3096-3096/com.example.gavin.wifiattendance D/Your App Name Here﹕ https://docs.google.com/forms/d/1yipuuXd5V53Ol12U24Cl2H4RIdYtm622jIk13Zo26cM/formResponse?entry_272641491=Hello&entry_130393492=World
03-12 15:06:27.428 3096-3096/com.example.gavin.wifiattendance E/WifiAttendance﹕ HttpUtils: android.os.NetworkOnMainThreadException
03-12 15:06:27.428 3096-3096/com.example.gavin.wifiattendance D/WifiAttendance﹕ Returning value:null
I am getting the feeling that i am supposed to create an Async task
for this
Correct. NetworkOnMainThreadException is thrown when you are trying to make network calls on your Main Thread (UI thread).
You can find a good tutorial on AsyncTask here.
Example from the tutorial:
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
//Do your network calls here
return response;
}
#Override
protected void onPostExecute(String result) {
//When you are done, this method runs on the UI thread so you can update the UI from here
textView.setText(result);
}
}
Finally you execute it like so
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://www.vogella.com" });
Thank you for the #Marcus for the helpful links i managed to get it working using this code:
public class PostDataTask extends AsyncTask<String, Void, Integer>{
#Override
protected Integer doInBackground(String... params) {
HttpRequest mReq = new HttpRequest();
String data = "entry_272641491=" + URLEncoder.encode(params[1]) + "&" +
"entry_130393492=" + URLEncoder.encode(params[2]);
String response = mReq.sendPost(params[0], data);
return 200;
}
}
My application pulls data from a web service that generates different sections for each user. Then I am going to use these sections to create tabs using FragmentPagerAdapter.
I have used an Async task to pull data from the web service. However the overridden methods such as getCount() and getPageTitle() in the FragmentPagerAdapter executed prior to my asynctask and completes its job. How can I prevent this and generate dynamic number of tabs and their title name based on the data fetched from the web service?
In other words how can I create dynamic number of tabs and titles based on the data fetch from the web service
My Code for FragmentPagerAdapter as below. As you can see I have hard coded the amount of tabs as well as their title names.
public class SectionsPagerAdapter extends FragmentPagerAdapter{
private boolean proceedStatus = false;
private String requestURL = "xxxxxxxxxxxxxxxxxxxxxxxx";
//list of fragments need to be added dynamically
public final ArrayList<Fragment> screens = new ArrayList<Fragment>();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new SectionFragment();
Bundle args = new Bundle();
args.putInt(SectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return "Camera".toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
case 3:
return "SECTION 4";
}
return null;
}
//setting the section title
private void setSectionTitle(){
}
//count the number of sections
private int countNumberofSections(){
int numberOfSection = 0;
return numberOfSection;
}
}
Then I have my Fragment code as below which has the the caller to the Async Task
public static class SectionFragment extends Fragment implements OnTaskCompleted {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private Slider adapter;
private ViewPager viewPager;
public static final String ARG_SECTION_NUMBER = "section_number";
Button thumbUpBut;
Button thumbDownBut;
Button captureButton;
ImageView genImage;
TextView genCaption;
private Camera mCamera;
private CameraPreview mPreview;
private static File mediaFile;
private ProgressDialog progress;
private static String imageSaveLocation;
private static String file_name_without_extension;
private ImageView imageView;
private Button uploadButton;
private Button cancelButton;
private Collection<Place> places = null;
private Collection<Happenings> events = null;
private Collection<General> general = null;
private ArrayList<String> sections;
public int getNumberOfPages(){
return sections.size();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy,container, false);
TextView dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
FeedRequest task = new FeedRequest(this);
task.execute("xxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
captureButton = (Button) rootView.findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takePhoto();
}
});
thumbUpBut = (Button) rootView.findViewById(R.id.thumbUp);
thumbUpBut.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.v("thumbPress", "thumbPressUp");
thumb("up");
}
});
thumbDownBut = (Button) rootView.findViewById(R.id.thumbDown);
thumbDownBut.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.v("thumbPress", "thumbPressDown");
thumb("down");
}
});
//allocating the activity one to the camera
if(getArguments().getInt(ARG_SECTION_NUMBER) == 1){
mCamera = getCameraInstance();
mPreview = new CameraPreview(this.getActivity(), mCamera);
FrameLayout preview = (FrameLayout)rootView.findViewById(R.id.camera_preview);
preview.addView(mPreview);
//hide buttons
thumbDownBut.setVisibility(rootView.INVISIBLE);
thumbUpBut.setVisibility(rootView.INVISIBLE);
}else{
thumbDownBut.setVisibility(rootView.VISIBLE);
thumbUpBut.setVisibility(rootView.VISIBLE);
captureButton.setVisibility(rootView.INVISIBLE);
}
viewPager = (ViewPager) rootView.findViewById(R.id.pager);
return rootView;
}
//take photo function
private void takePhoto() {
//get coordinates of the location
UserLocation userLocation = new UserLocation();
userLocation.getUserLocation(getActivity());
coordinates[0] = userLocation.longitude;
coordinates[1] = userLocation.latitude;
PictureCallback pictureCB = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera cam) {
new SavePhotoAndMetadata().execute(data);
cam.startPreview();
}
};
mCamera.takePicture(null, null, pictureCB);
}
//get camera instance
private Camera getCameraInstance() {
Camera camera = null;
try {
camera = Camera.open();
} catch (Exception e) {
// cannot get camera or does not exist
}
return camera;
}
//get the media out
private static File getOutputMediaFile() {
File mediaStorageDir = new File(Environment.getExternalStorageDirectory() + "/Android/data/asia.ceynet.realsnap/temp_img");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = (DateFormat.format("dd-MM-yyyy hh:mm:ss", new java.util.Date()).toString());
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
file_name_without_extension = "IMG_" + timeStamp;
imageSaveLocation = mediaFile.toString();
return mediaFile;
}
//saving the image and metadata together
class SavePhotoAndMetadata extends AsyncTask<byte[], String, String> {
#Override
protected String doInBackground(byte[]... data) {
File picFile = getOutputMediaFile();
if (picFile == null) {
return null;
}
byte[] photoData = data[0];
try {
//save the image
FileOutputStream fos = new FileOutputStream(picFile);
fos.write(photoData);
fos.close();
} catch (FileNotFoundException e) {
e.getStackTrace();
} catch (IOException e) {
e.getStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progress = new ProgressDialog(getActivity());
progress.setMessage("Saving Picture..Please wait...");
progress.show();
}
#Override
protected void onPostExecute(String s) {
progress.dismiss();
imagePreviewDialog();
}
}
//save image metadata in async task
class SaveMetadataTask extends AsyncTask<Void, String, Void> {
#Override
protected Void doInBackground(Void... params) {
serializeDeserialize.serializeData("This is for testing", file_name_without_extension, Double.toString(coordinates[0]), Double.toString(coordinates[1]), deviceId, deviceEmail);
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Void v) {
}
}
//image preview dialog and its functionality
private void imagePreviewDialog(){
//setting the bitmap
Bitmap bmp = BitmapFactory.decodeFile(mediaFile.toString());
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Image Preview");
builder.setCancelable(false);
LayoutInflater inflater = getActivity().getLayoutInflater();
ViewGroup vg = (ViewGroup)inflater.inflate(R.layout.sanp_preview_layout, null);
ImageView image = (ImageView) vg.findViewById(R.id.imageView);
image.setImageBitmap(rotateBitmap(bmp));
builder.setView(vg);
//buttons
builder.setPositiveButton("Upload",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
if(checkInternetConnection.haveNetworkConnection(sContext)){
//upload the image
uploadImage();
//save image metadata
new SaveMetadataTask().execute();
}else{
Toast.makeText(sContext, "Error! No internet connection detected. Image will be uploaded on an active internet connection", Toast.LENGTH_LONG).show();
new SaveMetadataTask().execute();
}
}
});
builder.setNegativeButton("Discard",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
discardImage(mediaFile.toString());
dialog.dismiss();
}
});
builder.show();
}
private Bitmap rotateBitmap(Bitmap image){
int width=image.getHeight();
int height=image.getWidth();
Bitmap srcBitmap=Bitmap.createBitmap(width, height, image.getConfig());
for (int y=width-1;y>=0;y--)
for(int x=0;x<height;x++)
srcBitmap.setPixel(width-y-1, x,image.getPixel(x, y));
return srcBitmap;
}
//device email
private String getDeviceEmail(){
AccountManager accountManager = AccountManager.get(sContext);
Account[] account = accountManager.getAccountsByType("com.google");
//device email
for(Account accLoop : account){
deviceEmail = accLoop.name;
}
return deviceEmail;
}
//upload image to the server
private void uploadImage(){
//save metadata
//call upload service
Intent intent = new Intent(sContext, HttpUploader.class);
Bundle loc = new Bundle();
loc.putDoubleArray("ss", coordinates);
intent.putExtra("url", PHOTO_UPLOAD);
intent.putExtra("paths", mediaFile.toString());
intent.putExtra("deviceid", deviceId);
intent.putExtra("deviceemail", getDeviceEmail());
intent.putExtra("posttext", "This is for testing");
intent.putExtra("filename", file_name_without_extension);
intent.putExtra("geo", loc);
sContext.startService(intent);
Toast.makeText(getActivity(), "Your image is being uploaded", Toast.LENGTH_LONG).show();
}
//discard image when the discard button is pressed
private void discardImage(String imagePath){
File file = new File(imagePath);
try{
file.delete();
}catch(Exception e){
Log.e("IMAGE_DELETION_ERROR", e.toString());
}
}
#Override
public void onTaskCompleted(boolean status, String message) {
// TODO Auto-generated method stub
Log.e("onTaskCompleted", "success" + status);
if (message == "tumb UP success") {
thumbUpBut.setSelected(true);
thumbDownBut.setSelected(false);
Log.e("tumb", "tumb");
} else if (message == "tumb DOWN success") {
thumbDownBut.setSelected(true);
thumbUpBut.setSelected(false);
Log.e("tumb", "tumb");
}
}
//listener for fetching main objects
#Override
public void onFeedCompleted(ArrayList<Posts> postArray, Multimap<String, Object> multiMap) {
// TODO Auto-generated method stub
numberOfPages = postArray.size();
adapter = new Slider(getActivity(), postArray, getContext());
viewPager.setAdapter(adapter);
// displaying selected image first
viewPager.setCurrentItem(postArray.size());
//saving the keyset
Set<String> keys = multiMap.keySet();
sections = new ArrayList<String>();
//sorting the categories and creating the category list
for(String key:keys){
//getting category list
if(!sections.contains(keys)){
sections.add(key);
}
//sorting categories
if(key.equals("Place")){
places.add((Place) multiMap.get(key));
}else if(key.equals("Events")){
events.add((Happenings) multiMap.get(key));
}else if(key.equals("General")){
general.add((General) multiMap.get(key));
}
}
}
//adding the pages to the adaptor dynamically
public void addPagesDynamically(){
}
}
//create the parent directory
private void createParentDiectory(){
File dir = new File(Environment.getExternalStorageDirectory() + "/Android/data/asia.ceynet.realsnap");
if(!(dir.exists() && dir.isDirectory())) {
dir.mkdirs();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_post:
openPost();
return true;
case R.id.action_settings:
// openSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void openPost() {
/*
Intent i = new Intent(getApplicationContext(), PhotoActivity.class);
startActivity(i);
*/
}
public static void thumb(String type) {
SectionFragment d = new SectionFragment();
PostThumb task = new PostThumb(type, d);
task.execute("xxxxxxxxxxxxxxxxxxxxxxxxxxxx");
}
//broadcast receiver for picture upload
public class MyWebRequestReceiver extends BroadcastReceiver {
public static final String PROCESS_RESPONSE = "asia.ceynet.intent.action.PROCESS_RESPONSE";
#Override
public void onReceive(Context context, Intent intent) {
//String responseString = intent.getStringExtra(HttpUploader.RESPONSE_STRING);
String reponseMessage = intent.getStringExtra(HttpUploader.RESPONSE_MESSAGE);
String responseStatus = intent.getStringExtra(HttpUploader.RESPONSE_STATUS);
String file_to_be_deleted = intent.getStringExtra(HttpUploader.FILE_NAME_WITHOUT_EXTENSION);
Toast.makeText(getApplicationContext(), reponseMessage + " - " + file_to_be_deleted + ".jpg", Toast.LENGTH_LONG).show();
//if uploaded successfully delete or image and metadata
if(responseStatus.equals("true")){
File temp_image_dir = new File(Environment.getExternalStorageDirectory() + "/Android/data/asia.ceynet.realsnap/temp_img/" + file_to_be_deleted + ".jpg");
File metadata_file = new File(Environment.getExternalStorageDirectory() + "/Android/data/asia.ceynet.realsnap/temp_img/" + file_to_be_deleted + ".ser");
try{
temp_image_dir.delete();
metadata_file.delete();
}catch(Exception e){
Log.e("IMAGE_DELETION_ERROR", e.toString());
}
}
}
}
When you finnish pulling the async data, provide the adapter with the new data and call .notifyDataSetChanged() on that adapter instance and the framework will update the pages and count by itself.
If you wish a more detailed explanation post your FragmentPagerAdapter implementation.
First of all, let me apologize if I'm not making myself clear enough because this is one of my first participation(s) here. But I'll be always here to answer queries related to this answer and clear any confusions arose by my statements.
Since you're using fragments, so I'm assuming you must have included your fragments inside an activity (lets say MainActivity.java).
What you need, can be done inside that activity containing fragment.
Here is the example code of onCreate method inside the MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fragmentManager = getSupportFragmentManager();
//Instance of viewpager included inside activity_main.xml
viewPager = (ViewPager) findViewById(R.id.vpMain);
SectionsPagerAdapter adapter = new SectionsPagerAdapter (fragmentManager);
//Adding some fragments right from the beginning, you could ignore it if not needed.
addFragments();
//This `OnPageChangeListener` will do the trick for you.
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
//Show the title of fragment
Toast.makeText(MainActivity.this, adapter.screens.get(position), Toast.LENGTH_SHORT).show();
//If fragment being loaded is later than the first one,
// then add one more fragment after the last fragment to the adapter.
// integer currentPosition is declared as a field, outside onCreate method and initially set to 0.
if(position>currentPosition){
currentPosition+=1;
adapter.addFragment(new SectionFragment(), "Fragment"+String.valueOf(position+3));
adapter.notifyDataSetChanged();
}else{
currentPosition--;
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
} // onCreate ends here.
Create this method inside your MainActivity (just to add 3 fragments to give your application a head-start.
private void addFragments(){
adapter.addFragment(new SectionFragment());
adapter.addFragment(new SectionFragment());
adapter.addFragment(new SectionFragment());
}
Then modify your SectionsPagerAdapter's getItem and getCount methods as below:
public class SectionsPagerAdapter extends FragmentPagerAdapter{
private boolean proceedStatus = false;
private String requestURL = "xxxxxxxxxxxxxxxxxxxxxxxx";
//list of fragments need to be added dynamically
public final ArrayList<Fragment> screens = new ArrayList<Fragment>();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return screens.get(position);
}
#Override
public int getCount() {
return screens.size();
}
//This method will dynamically add a fragment each time it is called.
public void addFragment(Fragment fragment) {
screens.add(fragment);
}
Now, no work related to "adding new fragment to the list" needs to be done inside your SectionFragment class.