Menu not displaying/flashes up momentarily and disappears - java

having an issue with getting an options menu to display from a fragment. If I don't have any of the code in the main activity portion nothing happens. After adding onCreateOptionsMenu to the main activity the icon appears momentarily in the toolbar, but then disappears, almost as if the view is being repainted?
Update:
Removed the onCreateOptionsMenu and onOptionsItemSelected from the fragment. Corrected the missing #Override on the onOptionsItemSelected in the activity. Issues persist. See updated WallpaperActivity.java below.
Updated WallpaperActivity.java
package com.death2all110.blisspapers;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.widget.ImageButton;
import android.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import com.koushikdutta.urlimageviewhelper.UrlImageViewCallback;
import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
public class WallpaperActivity extends Activity {
public final String TAG = "BlissPapers";
protected static final String MANIFEST = "wallpaper_manifest.xml";
protected static final int THUMBS_TO_SHOW = 4;
/*
* pull the manifest from the web server specified in config.xml or pull
* wallpaper_manifest.xml from local assets/ folder for testing
*/
public static final boolean USE_LOCAL_MANIFEST = false;
ArrayList<WallpaperCategory> categories = null;
ProgressDialog mLoadingDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(getResources().getColor(R.color.primary_dark));
setContentView(R.layout.activity_wallpaper);
mLoadingDialog = new ProgressDialog(this);
mLoadingDialog.setCancelable(false);
mLoadingDialog.setIndeterminate(true);
mLoadingDialog.setMessage("Retreiving wallpapers from server...");
mLoadingDialog.show();
new LoadWallpaperManifest().execute();
UrlImageViewHelper.setErrorDrawable(getResources().getDrawable(com.death2all110.blisspapers.R.drawable.ic_error));
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_about:
Intent intent = new Intent(this, About.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onResume() {
super.onResume();
Wallpaper.wallpapersCreated = 0;
}
protected void loadPreviewFragment() {
Toolbar ab = (Toolbar) findViewById(R.id.toolbar);
setActionBar(ab);
WallpaperPreviewFragment fragment = new WallpaperPreviewFragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.add(android.R.id.content, fragment);
ft.commit();
}
public static class WallpaperPreviewFragment extends Fragment {
static final String TAG = "PreviewFragment";
WallpaperActivity mActivity;
View mView;
public int currentPage = -1;
public int highestExistingIndex = 0;
ImageButton back;
ImageButton next;
TextView pageNum;
ThumbnailView[] thumbs;
protected int selectedCategory = 0; // *should* be <ALL> wallpapers
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mActivity = (WallpaperActivity) getActivity();
next(); // load initial page
}
public void setCategory(int cat) {
selectedCategory = cat;
currentPage = -1;
next();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mView = inflater.inflate(com.death2all110.blisspapers.R.layout.activity_wallpaper, container, false);
back = (ImageButton) mView.findViewById(com.death2all110.blisspapers.R.id.backButton);
next = (ImageButton) mView.findViewById(com.death2all110.blisspapers.R.id.nextButton);
pageNum = (TextView) mView.findViewById(com.death2all110.blisspapers.R.id.textView1);
thumbs = new ThumbnailView[THUMBS_TO_SHOW];
thumbs[0] = (ThumbnailView) mView.findViewById(com.death2all110.blisspapers.R.id.imageView1);
thumbs[1] = (ThumbnailView) mView.findViewById(com.death2all110.blisspapers.R.id.imageView2);
thumbs[2] = (ThumbnailView) mView.findViewById(com.death2all110.blisspapers.R.id.imageView3);
thumbs[3] = (ThumbnailView) mView.findViewById(com.death2all110.blisspapers.R.id.imageView4);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
next();
}
});
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
previous();
}
});
return mView;
}
public ArrayList<WallpaperCategory> getCategories() {
return mActivity.categories;
}
protected Wallpaper getWallpaper(int realIndex) {
return getCategories().get(selectedCategory).getWallpapers().get(realIndex);
}
protected void setThumbs() {
for (ThumbnailView v : thumbs)
v.setVisibility(View.INVISIBLE);
final int numWallpapersInCategory = getCategories().get(selectedCategory)
.getWallpapers().size();
boolean enableForward = true;
for (int i = 0; i < thumbs.length; i++) {
final int realIndex = (currentPage * thumbs.length + i);
if (realIndex >= (numWallpapersInCategory - 1)) {
enableForward = false;
break;
}
Wallpaper w = getWallpaper(realIndex);
thumbs[i].setOnClickListener(null);
thumbs[i].getName().setText(w.getName());
thumbs[i].getAuthor().setText(w.getAuthor());
UrlImageViewHelper.setUrlDrawable(thumbs[i].getThumbnail(), w.getThumbUrl(),
com.death2all110.blisspapers.R.drawable.ic_placeholder, new ThumbnailCallBack(w, realIndex));
}
back.setEnabled(currentPage != 0);
next.setEnabled(enableForward);
}
public void next() {
getNextButton().setEnabled(false);
pageNum.setText(getResources().getString(com.death2all110.blisspapers.R.string.page) + " " + (++currentPage + 1));
setThumbs();
}
public void previous() {
pageNum.setText(getResources().getString(com.death2all110.blisspapers.R.string.page) + " " + (--currentPage + 1));
setThumbs();
}
protected void skipToPage(int page) {
if (page < currentPage) {
while (page < currentPage) {
previous(); // should subtract page
}
} else if (page > currentPage) {
while (page > currentPage) {
next();
}
}
}
protected View getThumbView(int i) {
if (thumbs != null && thumbs.length > 0)
return thumbs[i];
else
return null;
}
protected ImageButton getNextButton() {
return next;
}
protected ImageButton getPreviousButton() {
return back;
}
class ThumbnailCallBack implements UrlImageViewCallback {
Wallpaper wall;
int index;
public ThumbnailCallBack(Wallpaper wall, int index) {
this.wall = wall;
this.index = index;
}
#Override
public void onLoaded(ImageView imageView, Drawable loadedDrawable, String url,
boolean loadedFromCache, boolean error) {
final int relativeIndex = index % 4;
if (!error) {
getThumbView(relativeIndex).setOnClickListener(
new ThumbnailClickListener(wall));
}
getThumbView(relativeIndex).setVisibility(View.VISIBLE);
if (relativeIndex == 3)
getNextButton().setEnabled(true);
}
}
class ThumbnailClickListener implements View.OnClickListener {
Wallpaper wall;
public ThumbnailClickListener(Wallpaper wallpaper) {
this.wall = wallpaper;
}
#Override
public void onClick(View v) {
Intent preview = new Intent(mActivity, Preview.class);
preview.putExtra("wp", wall.getUrl());
startActivity(preview);
}
}
}
public static String getDlDir(Context c) {
String configFolder = getResourceString(c, com.death2all110.blisspapers.R.string.config_wallpaper_download_loc);
if (configFolder != null && !configFolder.isEmpty()) {
return new File(Environment.getExternalStorageDirectory(), configFolder)
.getAbsolutePath() + "/";
} else {
return Environment.getExternalStorageDirectory().getAbsolutePath();
}
}
public static String getSvDir(Context c) {
String configFolder = getResourceString(c, com.death2all110.blisspapers.R.string.config_wallpaper_sdcard_dl_location);
if (configFolder != null && !configFolder.isEmpty()) {
return new File(Environment.getExternalStorageDirectory(), configFolder)
.getAbsolutePath() + "/";
} else {
return null;
}
}
protected String getWallpaperDestinationPath() {
String configFolder = getResourceString(com.death2all110.blisspapers.R.string.config_wallpaper_sdcard_dl_location);
if (configFolder != null && !configFolder.isEmpty()) {
return new File(Environment.getExternalStorageDirectory(), configFolder)
.getAbsolutePath();
}
// couldn't find resource?
return null;
}
protected String getResourceString(int stringId) {
return getApplicationContext().getResources().getString(stringId);
}
public static String getResourceString(Context c, int id) {
return c.getResources().getString(id);
}
private class LoadWallpaperManifest extends
AsyncTask<Void, Boolean, ArrayList<WallpaperCategory>> {
#Override
protected ArrayList<WallpaperCategory> doInBackground(Void... v) {
try {
InputStream input = null;
if (USE_LOCAL_MANIFEST) {
input = getApplicationContext().getAssets().open(MANIFEST);
} else {
URL url = new URL(getResourceString(com.death2all110.blisspapers.R.string.config_wallpaper_manifest_url));
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical
// 0-100%
// progress bar
int fileLength = connection.getContentLength();
// download the file
input = new BufferedInputStream(url.openStream());
}
OutputStream output = getApplicationContext().openFileOutput(
MANIFEST, MODE_PRIVATE);
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
// file finished downloading, parse it!
ManifestXmlParser parser = new ManifestXmlParser();
return parser.parse(new File(getApplicationContext().getFilesDir(), MANIFEST),
getApplicationContext());
} catch (Exception e) {
Log.d(TAG, "Exception!", e);
}
return null;
}
#Override
protected void onPostExecute(ArrayList<WallpaperCategory> result) {
categories = result;
if (categories != null)
loadPreviewFragment();
mLoadingDialog.cancel();
super.onPostExecute(result);
}
}
}
Menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/action_about"
android:icon="#drawable/ic_menu_info"
android:title="#string/action_about"
android:showAsAction="always">
</item>
</menu>

In your onCreate() method for your fragment, try adding this one line of code:
setHasOptionsMenu(true);
Android API reference: enter link description here
I had the same problem when implementing a menu from a fragment

To me you should keep only one reference to onCreateOptionsMenu() and onOptionsItemSelected(). Since the fragment is hosted inside the Activity, it's enough to manage options menu from there. So:
Delete all instances of onCreateOptionsMenu() and onOptionsItemSelected() from your fragment;
Delete all instances of setHasOptionsMenu(true) you previously added;
In your Activity, just keep:
#Override
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
...
Note that in your code #Override is missing here and there.
That said, why are onCreateOptionsMenu() and onOptionsItemSelected() methods also available for fragments? Because if you have multiple fragments that can be shown in the same Activity, you might want to have each fragment add some items to the Activity OptionsMenu.
That is done with setHasOptionsMenu(true) and there are a lot of questions already answered here on the topic. But, as per what you said, that's not your case. You just want an Activity menu, so forget about the fragment.
The menu disappearing was you calling menu.clear().

Got it figured out.
I removed
Toolbar ab = (Toolbar) findViewById(R.id.toolbar);
setActionBar(ab);
from the loadPreviewFragment()
Then removed the Toolbar view from my activity_wallpaper.xml layout
And changed the parent theme in my style.xml from
parent=Theme.Material.NoActionBar
to
parent=Theme.Material
Thanks for the help guys.

Related

How to send data sent by BLE Device in a fragment to a new activity for display and plotting graph in app?

I am completely new to Android and just learned Object-oriented programming. My project requires me to build something on open-source code. I am really struggling with this special case. Two fragments are under activity_main, one of them is TerminalFragment. I added a menuItem (R.id.plot) in it and set if the user clicks this Item that will lead him from TerminalFragment to activity_main2. Due to receive(byte data) and TerminalFragment still on active, the data is still printing out by receiveText.append(TextUtil.toCaretString(msg, newline.length() != 0)); in activity_main.
Now, I want to convert the data to String and send it to activity_main2 for display in recyclerview and plotting graph. I am trying to use putextra and getextra but not sure how to access data from getextra in activity_main2. In my testing, the recyclerview just showed "John". Is something missing in my method? Does anyone have a better idea? Much Appreciated.
TerminalFragment
package de.kai_morich.simple_bluetooth_le_terminal;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.ScrollingMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.EditText;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
public class TerminalFragment extends Fragment implements ServiceConnection, SerialListener {
private MenuItem menuItem;
private enum Connected { False, Pending, True }
private String deviceAddress;
private SerialService service;
private TextView receiveText;
private TextView sendText;
private TextUtil.HexWatcher hexWatcher;
private Connected connected = Connected.False;
private boolean initialStart = true;
private boolean hexEnabled = false;
private boolean pendingNewline = false;
private String newline = TextUtil.newline_crlf;
private String output;
/*
* Lifecycle
*/
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
//Register with activity
// You must inform the system that your app bar fragment is participating in the population of the options menu.
// tells the system that your fragment would like to receive menu-related callbacks.
setRetainInstance(true);
deviceAddress = getArguments().getString("device");
}
#Override
public void onDestroy() {
if (connected != Connected.False)
disconnect();
getActivity().stopService(new Intent(getActivity(), SerialService.class));
super.onDestroy();
}
#Override
public void onStart() {
super.onStart();
if(service != null)
service.attach(this);
else
getActivity().startService(new Intent(getActivity(), SerialService.class)); // prevents service destroy on unbind from recreated activity caused by orientation change
}
#Override
public void onStop() {
if(service != null && !getActivity().isChangingConfigurations())
service.detach();
super.onStop();
}
#SuppressWarnings("deprecation") // onAttach(context) was added with API 23. onAttach(activity) works for all API versions
#Override
public void onAttach(#NonNull Activity activity) {
super.onAttach(activity);
getActivity().bindService(new Intent(getActivity(), SerialService.class), this, Context.BIND_AUTO_CREATE);
}
#Override
public void onDetach() {
try { getActivity().unbindService(this); } catch(Exception ignored) {}
super.onDetach();
}
#Override
public void onResume() {
super.onResume();
if(initialStart && service != null) {
initialStart = false;
getActivity().runOnUiThread(this::connect);
}
}
#Override
public void onServiceConnected(ComponentName name, IBinder binder) {
service = ((SerialService.SerialBinder) binder).getService();
service.attach(this);
if(initialStart && isResumed()) {
initialStart = false;
getActivity().runOnUiThread(this::connect);
}
}
#Override
public void onServiceDisconnected(ComponentName name) {
service = null;
}
/*
* UI
*/
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_terminal, container, false);
receiveText = view.findViewById(R.id.receive_text); // TextView performance decreases with number of spans
receiveText.setTextColor(getResources().getColor(R.color.colorRecieveText)); // set as default color to reduce number of spans
receiveText.setMovementMethod(ScrollingMovementMethod.getInstance());
sendText = view.findViewById(R.id.send_text);
hexWatcher = new TextUtil.HexWatcher(sendText);
hexWatcher.enable(hexEnabled);
sendText.addTextChangedListener(hexWatcher);
sendText.setHint(hexEnabled ? "HEX mode" : "");
View sendBtn = view.findViewById(R.id.send_btn);
sendBtn.setOnClickListener(v -> send(sendText.getText().toString()));
return view;
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_terminal, menu);
menu.findItem(R.id.hex).setChecked(hexEnabled);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.clear) {
receiveText.setText("");
return true;
} if (id == R.id.plot){
Intent intent = new Intent(getActivity(), MainActivity2.class);
startActivity(intent);
//receive.;
return true;
}else if (id == R.id.newline) {
String[] newlineNames = getResources().getStringArray(R.array.newline_names);
String[] newlineValues = getResources().getStringArray(R.array.newline_values);
int pos = java.util.Arrays.asList(newlineValues).indexOf(newline);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Newline");
builder.setSingleChoiceItems(newlineNames, pos, (dialog, item1) -> {
newline = newlineValues[item1];
dialog.dismiss();
});
builder.create().show();
return true;
} else if (id == R.id.hex) {
hexEnabled = !hexEnabled;
sendText.setText("");
hexWatcher.enable(hexEnabled);
sendText.setHint(hexEnabled ? "HEX mode" : "");
item.setChecked(hexEnabled);
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
/*
* Serial + UI
*/
private void connect() {
try {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
status("connecting...");
connected = Connected.Pending;
SerialSocket socket = new SerialSocket(getActivity().getApplicationContext(), device);
service.connect(socket);
} catch (Exception e) {
onSerialConnectError(e);
}
}
private void disconnect() {
connected = Connected.False;
service.disconnect();
}
private void send(String str) {
if(connected != Connected.True) {
Toast.makeText(getActivity(), "not connected", Toast.LENGTH_SHORT).show();
return;
}
try {
String msg;
byte[] data;
if(hexEnabled) {
StringBuilder sb = new StringBuilder();
TextUtil.toHexString(sb, TextUtil.fromHexString(str));
TextUtil.toHexString(sb, newline.getBytes());
msg = sb.toString();
data = TextUtil.fromHexString(msg);
} else {
msg = str;
data = (str + newline).getBytes();
}
SpannableStringBuilder spn = new SpannableStringBuilder(msg + '\n');
spn.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorSendText)), 0, spn.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
receiveText.append(spn);
service.write(data);
} catch (Exception e) {
onSerialIoError(e);
}
}
private void receive(byte[] data) {
if(hexEnabled) {
receiveText.append("Hello" + TextUtil.toHexString(data) + '\n');
} else {
String msg = new String(data);
if(newline.equals(TextUtil.newline_crlf) && msg.length() > 0) {
// don't show CR as ^M if directly before LF
msg = msg.replace(TextUtil.newline_crlf, TextUtil.newline_lf);
// special handling if CR and LF come in separate fragments
if (pendingNewline && msg.charAt(0) == '\n') {
Editable edt = receiveText.getEditableText();
if (edt != null && edt.length() > 1)
edt.replace(edt.length() - 2, edt.length(), "");
}
pendingNewline = msg.charAt(msg.length() - 1) == '\r';
}
receiveText.append(TextUtil.toCaretString(msg, newline.length() != 0)); //print out data
output = receiveText.toString(); // CharSequence to String
Intent intent = new Intent(getActivity(), MainActivity2.class);
intent.putExtra("output",output); // send data to next activity, MainActivity2
}
}
private void status(String str) {
SpannableStringBuilder spn = new SpannableStringBuilder(str + '\n');
spn.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorStatusText)), 0, spn.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
receiveText.append(spn);
}
/*
* SerialListener
*/
#Override
public void onSerialConnect() {
status("connected");
connected = Connected.True;
}
#Override
public void onSerialConnectError(Exception e) {
status("connection failed: " + e.getMessage());
disconnect();
}
#Override
public void onSerialRead(byte[] data) {// receive data
receive(data); // send data to printout
}
#Override
public void onSerialIoError(Exception e) {
status("connection lost: " + e.getMessage());
disconnect();
}
}
MainActivity2.java (new activity)
package de.kai_morich.simple_bluetooth_le_terminal;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity2 extends AppCompatActivity {
Fragment CustomFragment;
private ArrayList<Data> dataList;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = findViewById(R.id.toolbar2);
setSupportActionBar(toolbar);
recyclerView = findViewById(R.id.dataflow);
dataList = new ArrayList<>();
String data;
if (savedInstanceState == null) {
Bundle extra = getIntent().getExtras();
if (extra == null) {
data = null;
receiveData(data);
} else {
data = extra.getString("output");
receiveData(data);
}
} else {
data = (String) savedInstanceState.getSerializable("output");
receiveData(data);
}
setAdapter();
}
private void receiveData(String data){
String Data = data;
dataList.add(new Data("John"));
dataList.add(new Data(Data));
}
private void setAdapter() {
recyclerAdapter adapter = new recyclerAdapter(dataList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_plot, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.dataplot:
Toast.makeText(this, "dataplot", Toast.LENGTH_SHORT).show();
replaceFragment(new DataPlotFragment());
return true;
case R.id.fft:
Toast.makeText(this, "FFT", Toast.LENGTH_SHORT).show();
replaceFragment(new FftFragment());
return true;
case R.id.data:
Toast.makeText(this, "DATA", Toast.LENGTH_SHORT).show();
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void replaceFragment(Fragment fragment){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.plotframelayout,fragment);
fragmentTransaction.commit();
}
}
I realized I also need to add getText() in receive(). However, the recycler view won't update itself, it just captures what it has in the recyclerview of activity_main with TerminalFragment when the user click the menuItem (id,plot). Either getextrastring() or using bundle able to pass the data to Mainactivity2.
I think I need to add something else to keep adding data to the recyclerview of activity_main2 from activity_main.
onOptionsItemSelected of TerminalFragment
if (id == R.id.plot){
Intent intent = new Intent(getActivity(), MainActivity2.class);
intent.putExtra("output",output); //output
startActivity(intent);
return true;
}
receive() of TerminalFragment
private void receive(byte[] data) {
if(hexEnabled) {
receiveText.append("Hello" + TextUtil.toHexString(data) + '\n');
} else {
String msg = new String(data);
if(newline.equals(TextUtil.newline_crlf) && msg.length() > 0) {
// don't show CR as ^M if directly before LF
msg = msg.replace(TextUtil.newline_crlf, TextUtil.newline_lf);
// special handling if CR and LF come in separate fragments
if (pendingNewline && msg.charAt(0) == '\n') {
Editable edt = receiveText.getEditableText();
if (edt != null && edt.length() > 1)
edt.replace(edt.length() - 2, edt.length(), "");
}
pendingNewline = msg.charAt(msg.length() - 1) == '\r';
}
receiveText.append(TextUtil.toCaretString(msg, newline.length() != 0)); //print out data
output = receiveText.getText().toString(); // CharSequence to String
}
}
OnCreate of mainActivity2
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = findViewById(R.id.toolbar2);
setSupportActionBar(toolbar);
recyclerView = findViewById(R.id.dataflow);
dataList = new ArrayList<>();
String data;
Bundle extras = getIntent().getExtras();
if (extras != null)
{
data = extras.getString("output");
receiveData(data);
}
setAdapter();
}

Navigation Bar transparent during video playback

The following code allows you to start a video player and play the video.
The problem is that the NavigationBar hides a piece of the video, I would like to make it transparent.
import android.app.Activity;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.Point;
import android.media.MediaPlayer;
import android.widget.MediaController;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.view.MotionEvent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.VideoView;
public class SimpleVideoStream extends Activity implements
MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener,
MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener {
private String TAG = getClass().getSimpleName();
private VideoView mVideoView = null;
private MediaPlayer mMediaPlayer = null;
private MediaController mMediaController = null;
private ProgressBar mProgressBar = null;
private String mVideoUrl;
private Boolean mShouldAutoClose = true;
private boolean mControls;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
Bundle b = getIntent().getExtras();
mVideoUrl = b.getString("mediaUrl");
mShouldAutoClose = b.getBoolean("shouldAutoClose", true);
mControls = b.getBoolean("controls", true);
RelativeLayout relLayout = new RelativeLayout(this);
relLayout.setBackgroundColor(Color.BLACK);
RelativeLayout.LayoutParams relLayoutParam = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
relLayoutParam.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
mVideoView = new VideoView(this);
mVideoView.setLayoutParams(relLayoutParam);
relLayout.addView(mVideoView);
// Create progress throbber
mProgressBar = new ProgressBar(this);
mProgressBar.setIndeterminate(true);
// Center the progress bar
RelativeLayout.LayoutParams pblp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
pblp.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
mProgressBar.setLayoutParams(pblp);
// Add progress throbber to view
relLayout.addView(mProgressBar);
mProgressBar.bringToFront();
setOrientation(b.getString("orientation"));
setContentView(relLayout, relLayoutParam);
play();
}
private void play() {
mProgressBar.setVisibility(View.VISIBLE);
Uri videoUri = Uri.parse(mVideoUrl);
try {
mVideoView.setOnCompletionListener(this);
mVideoView.setOnPreparedListener(this);
mVideoView.setOnErrorListener(this);
mVideoView.setVideoURI(videoUri);
mMediaController = new MediaController(this);
mMediaController.setAnchorView(mVideoView);
mMediaController.setMediaPlayer(mVideoView);
if (!mControls) {
mMediaController.setVisibility(View.GONE);
}
mVideoView.setMediaController(mMediaController);
} catch (Throwable t) {
Log.d(TAG, t.toString());
}
}
private void setOrientation(String orientation) {
if ("landscape".equals(orientation)) {
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}else if("portrait".equals(orientation)) {
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
private Runnable checkIfPlaying = new Runnable() {
#Override
public void run() {
if (mVideoView.getCurrentPosition() > 0) {
// Video is not at the very beginning anymore.
// Hide the progress bar.
mProgressBar.setVisibility(View.GONE);
} else {
// Video is still at the very beginning.
// Check again after a small amount of time.
mVideoView.postDelayed(checkIfPlaying, 100);
}
}
};
#Override
public void onPrepared(MediaPlayer mp) {
Log.d(TAG, "Stream is prepared");
mMediaPlayer = mp;
mMediaPlayer.setOnBufferingUpdateListener(this);
mVideoView.requestFocus();
mVideoView.start();
mVideoView.postDelayed(checkIfPlaying, 0);
}
private void pause() {
Log.d(TAG, "Pausing video.");
mVideoView.pause();
}
private void stop() {
Log.d(TAG, "Stopping video.");
mVideoView.stopPlayback();
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy triggered.");
stop();
}
private void wrapItUp(int resultCode, String message) {
Log.d(TAG, "wrapItUp was triggered.");
Intent intent = new Intent();
intent.putExtra("message", message);
setResult(resultCode, intent);
finish();
}
public void onCompletion(MediaPlayer mp) {
Log.d(TAG, "onCompletion triggered.");
stop();
if (mShouldAutoClose) {
wrapItUp(RESULT_OK, null);
}
}
public boolean onError(MediaPlayer mp, int what, int extra) {
StringBuilder sb = new StringBuilder();
sb.append("MediaPlayer Error: ");
switch (what) {
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
sb.append("Not Valid for Progressive Playback");
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
sb.append("Server Died");
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
sb.append("Unknown");
break;
default:
sb.append(" Non standard (");
sb.append(what);
sb.append(")");
}
sb.append(" (" + what + ") ");
sb.append(extra);
Log.e(TAG, sb.toString());
wrapItUp(RESULT_CANCELED, sb.toString());
return true;
}
public void onBufferingUpdate(MediaPlayer mp, int percent) {
Log.d(TAG, "onBufferingUpdate : " + percent + "%");
}
#Override
public void onBackPressed() {
// If we're leaving, let's finish the activity
wrapItUp(RESULT_OK, null);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// The screen size changed or the orientation changed... don't restart the activity
super.onConfigurationChanged(newConfig);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (mMediaController != null)
mMediaController.show();
return false;
}
}
I tried to add this, but it does not work very well, the problem is that the progressBar overlaps the NavigationBar, when the device is in portrait mode.
#Override
public boolean onTouchEvent(MotionEvent event) {
if (mMediaController != null){
mMediaController.show();
this.getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
| View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
| View.SYSTEM_UI_FLAG_IMMERSIVE
);
}
return false;
}

How to Show Different Strings With The Same Position When Clicking Random Button?

How to Show Different Strings With The Same Position When Clicking Random Button, So when the string is randomized the word and word2 display the same position data and in different textview. I have been looking for information for a few days and have not found an answer yet. I am confused to do so can you help me? Here's the Java file I have.
Adapter.java
package com.word.game;
import java.util.Random;
public class Adapter {
public static final Random RANDOM = new Random();
public static final String[] WORDS = {"RUN",
"WALK",
"CRY",
"SUGAR",
"SALT",
"RAIN",
"NOVEMBER"};
public static final String[] WORDS2 = {"FAST",
"RELAX",
"TEARS",
"DRINK",
"RECIPERS",
"WATER",
"CALENDAR"};
public static String randomWord2() {
return WORDS2[RANDOM.nextInt(WORDS2.length)];
}
public static String randomWord() {
return WORDS[RANDOM.nextInt(WORDS.length)];
}
public static String shuffleWord(String word) {
if (word != null && !"".equals(word)) {
char a[] = word.toCharArray();
for (int i = 0; i < a.length; i++) {
int j = RANDOM.nextInt(a.length);
char tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
return new String(a);
}
return word;
}
}
MainActivity.java
package com.papaozi.pilgub;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.InputFilter;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private MediaPlayer mediaPlayerbg, mediaPlayerwin, mediaPlayerSalah;
private TextView suffletext, quest;
private EditText answer;
private Button validate, newGame;
private String wordToFind, wordToFind2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
quest = (TextView) findViewById(R.id.quest);
suffletext = (TextView) findViewById(R.id.suffletext);
answer = (EditText) findViewById(R.id.wordEnteredEt);
validate = (Button) findViewById(R.id.validate);
validate.setOnClickListener(this);
newGame = (Button) findViewById(R.id.newGame);
newGame.setOnClickListener(this);
answer.setFilters(new InputFilter[]{new InputFilter.AllCaps()});
newGame();
initViews();
}
private void initViews() {
mediaPlayerbg = MediaPlayer.create(this, R.raw.spooky);
mediaPlayerbg.start();
mediaPlayerbg.setLooping(true);
}
#Override
public void onClick(View view) {
if (view == validate) {
validate();
} else if (view == newGame) {
newGame();
}
}
private void validate() {
String w = answer.getText().toString();
Context context = getApplicationContext();
LayoutInflater inflater = getLayoutInflater();
View customToastroot = inflater.inflate(R.layout.custom_toast_benar, null);
final Toast customtoast = new Toast(context);
customtoast.setView(customToastroot);
customtoast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.TOP, 0, 0);
customtoast.setDuration(Toast.LENGTH_LONG);
Context context2 = getApplicationContext();
LayoutInflater inflater2 = getLayoutInflater();
View customToastroot2 = inflater2.inflate(R.layout.custom_toast_salah, null);
final Toast customtoast2 = new Toast(context2);
customtoast2.setView(customToastroot2);
customtoast2.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.TOP, 0, 0);
customtoast2.setDuration(Toast.LENGTH_LONG);
if (wordToFind.equals(w)) {
customtoast.show();
newGame();
mediaPlayerwin = MediaPlayer.create(this, R.raw.winner);
mediaPlayerwin.start();
} else {
customtoast2.show();
mediaPlayerSalah = MediaPlayer.create(this, R.raw.draw);
mediaPlayerSalah.start();
}
}
private void newGame() {
wordToFind = Adapter.randomWord();
String wordShuffled = Adapter.shuffleWord(wordToFind);
suffletext.setText(wordShuffled);
answer.setText("");;
}
protected void onDestroy() {
super.onDestroy();
if (mediaPlayerbg != null) {
mediaPlayerbg.release();
mediaPlayerbg = null;
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
startActivity(new Intent(MainActivity.this, SecondActivity.class));
mediaPlayerbg.stop();
finish();
}
}
If you want to return same position in different arrays with same size,
Try this
public static String randomWord2(int pos) {
return WORDS2[pos];
}
public static String randomWord(int pos) {
return WORDS[pos];
}
public static int randomNum() {
return RANDOM.nextInt(WORDS.length);
}
When You are invoking randomWord() and randomWord2() , get the random position first and the pass it to the methods
int pos= randomNum();
word1=randomWord(pos);
word2=randomWord2(pos);

Error java.lang.NumberFormatException: Invalid double: "86,24" [duplicate]

This question already has answers here:
Best way to parseDouble with comma as decimal separator?
(10 answers)
Android NumberFormatException: Invalid Double - except the value is a valid Double
(2 answers)
Closed 6 years ago.
Android studio noti this error.This code by a main screen of quiz game
How to fix it??? i was try some guide but nothing
This is My error
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NumberFormatException: Invalid double: "86,24"
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.parseDouble(StringToReal.java:269)
at java.lang.Double.parseDouble(Double.java:295)
at gt.scratchgame.MainActivity.checkAns(MainActivity.java:345)
at gt.scratchgame.MainActivity.onClick(MainActivity.java:318)
at android.view.View.performClick(View.java:4084)
at android.view.View$PerformClick.run(View.java:16966)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
My activity
package gt.scratchgame;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.startapp.android.publish.StartAppAd;
import com.startapp.android.publish.StartAppSDK;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import gt.scratchgame.base.Session;
import gt.scratchgame.bean.AnsOptionBean;
import gt.scratchgame.bean.BeanEachQuetionScore;
import gt.scratchgame.bean.QuestionAnsbean;
import gt.scratchgame.constants.AppConstants;
import gt.scratchgame.database.DBhelper;
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private WScratchView scratchView;
private TextView percentageView, scorelabel, textViewNo, textViewcounter, textViewTotalScore, textView3;
private float mPercentage;
public DBhelper dbhelper;
AQuery aQuery;
private static QuestionAnsbean questionAnsbean1;
private static String trueAns = null;
private static int quetionNumber = 0;
protected Button gameActivityButton1, gameActivityButton2, gameActivityButton3, gameActivityButton4;
ImageView imageView;
Session session;
Bitmap bitmap;
Typeface typeface;
private static float totalScore = 0;
public List<QuestionAnsbean> questionAnsList;
private List<BeanEachQuetionScore> scoreList;
ProgressDialog dialog;
private StartAppAd startAppAd;
AdView mAdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
}
#Override
protected void onResume() {
super.onResume();
questionAnsList = new ArrayList<QuestionAnsbean>();
startAppAd = new StartAppAd(this);
aQuery = new AQuery(this);
session = Session.getInstance();
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.scratchview1);
scoreList = new ArrayList<BeanEachQuetionScore>();
scratchView = (WScratchView) findViewById(R.id.scratch_view);
scratchView.setScratchBitmap(bitmap);
typeface = Typeface.createFromAsset(getAssets(),"customestyle.TTF");
totalScore = 0;
quetionNumber = 0;
dialog = new ProgressDialog(this);
initDialogProperty();
asyncJson();
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
StartAppSDK.init(this, AppConstants.DEVELOPER_ID, AppConstants.APP_ID, true);
// StartAppAd.showSlider(this);
startAppAd.showAd();
}
private void initDialogProperty() {
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setIndeterminate(false);
dialog.setCancelable(false);
dialog.setMessage("Loading...");
}
private void initUI() {
percentageView = (TextView) findViewById(R.id.percentage);
percentageView.setTypeface(typeface);
scorelabel = (TextView) findViewById(R.id.scorelabel);
scorelabel.setTypeface(typeface);
textViewNo = (TextView) findViewById(R.id.textViewNo);
textViewNo.setTypeface(typeface);
textViewcounter = (TextView) findViewById(R.id.textViewcounter);
textViewcounter.setTypeface(typeface);
textViewTotalScore = (TextView) findViewById(R.id.textViewTotalScore);
textViewTotalScore.setTypeface(typeface);
textViewTotalScore.setText(totalScore + "");
textView3 = (TextView) findViewById(R.id.textView3);
textView3.setTypeface(typeface);
dbhelper = DBhelper.getInstance(getApplicationContext());
dbhelper.open();
initDb();
Collections.shuffle(questionAnsList);
/*Game Activity 4 option button*/
gameActivityButton1 = (Button) findViewById(R.id.gameActivityButton1);
gameActivityButton2 = (Button) findViewById(R.id.gameActivityButton2);
gameActivityButton3 = (Button) findViewById(R.id.gameActivityButton3);
gameActivityButton4 = (Button) findViewById(R.id.gameActivityButton4);
gameActivityButton1.setTypeface(typeface);
gameActivityButton2.setTypeface(typeface);
gameActivityButton3.setTypeface(typeface);
gameActivityButton4.setTypeface(typeface);
gameActivityButton1.setOnClickListener(this);
gameActivityButton2.setOnClickListener(this);
gameActivityButton3.setOnClickListener(this);
gameActivityButton4.setOnClickListener(this);
quetionInitialize();
// customize attribute programmatically
scratchView.setScratchable(true);
scratchView.setRevealSize(50);
scratchView.setAntiAlias(true);
// scratchView.setOverlayColor(Color.RED);
scratchView.setBackgroundClickable(true);
// add callback for update scratch percentage
scratchView.setOnScratchCallback(new WScratchView.OnScratchCallback() {
#Override
public void onScratch(float percentage) {
updatePercentage(percentage);
}
#Override
public void onDetach(boolean fingerDetach) {
/* if(mPercentage > 1){
scratchView.setScratchAll(true);
updatePercentage(100);
}*/
}
});
updatePercentage(0f);
}
private void updatePercentage(float percentage) {
mPercentage = percentage;
String percentage2decimal = String.format("%.2f", (100 - percentage));
percentageView.setText(percentage2decimal);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
/* #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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}*/
private void initDb() {
// Toast.makeText(getApplicationContext()," DB size-- "+dbhelper.getUserData().size(),Toast.LENGTH_LONG).show();
// dbhelper.addData(session.getSelectedCategory().id,"guru",123.36f);
}
public void asyncJson() {
// String url = "http://gurutechnolabs.com/demo/kids/demo.php?category=+""&level=level";
// Toast.makeText(getApplicationContext(),"aaaaaa",Toast.LENGTH_LONG).show();
int id = session.getSelectedCategory().id;
dialog.show();
String url = "http://8chan.biz/app/demo.php?category="+id;
Log.d("*************",url);
aQuery.ajax(url, JSONObject.class, new AjaxCallback<JSONObject>() {
#Override
public void callback(String url, JSONObject json, AjaxStatus status) {
if (json != null) {
try {
JSONObject mainJsonObject = new JSONObject(json.toString());
if(mainJsonObject != null)
{
JSONArray list = mainJsonObject.getJSONArray("data");
if(list != null)
{
for(int i = 0 ; i < list.length() ; i++)
{
JSONObject subObject = list.getJSONObject(i);
// aQuery.id(R.id.result).visible().text(subObject.toString());
QuestionAnsbean questionAnsbean = new QuestionAnsbean();
questionAnsbean.id = subObject.getInt("id");
questionAnsbean.cat_id = subObject.getInt("cat_id");
questionAnsbean.url = subObject.getString("url");
JSONArray questionAnsOptionArrary = subObject.getJSONArray("answers");
for (int j = 0; j < questionAnsOptionArrary.length(); j++)
{
JSONObject suObject1 = questionAnsOptionArrary.getJSONObject(j);
AnsOptionBean ansOptionBean = new AnsOptionBean();
ansOptionBean.answer = suObject1.getString("answer");
ansOptionBean.result = suObject1.getInt("result");
questionAnsbean.ansOptionList.add(ansOptionBean);
}
questionAnsList.add(questionAnsbean);
// session.setOperationLists1(questionAnsbean);
// Toast.makeText(getApplicationContext(),levelLists.size()+"",Toast.LENGTH_LONG).show();
//gameLevelGridAdapter.notifyDataSetChanged();
}
// Collections.shuffle(ansOptionList);
}
// Toast.makeText(getApplicationContext(),questionAnsList.size()+" This is list size in asin aquery ",Toast.LENGTH_LONG).show();
initUI();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Toast.makeText(getApplicationContext(), listItem.size()+"", Toast.LENGTH_LONG).show();
//showResult(json, status);
} else {
// ajax error, show error code
/* Toast.makeText(aQuery.getContext(),
"Error:" + status.getMessage(), Toast.LENGTH_LONG)
.show();*/
}
}
});
}
private void quetionInitialize() {
scratchView.resetView();
scratchView.setScratchAll(false);
textViewcounter.setText(quetionNumber+"");
questionAnsbean1 = new QuestionAnsbean();
questionAnsbean1 = questionAnsList.get(quetionNumber);
dialog.dismiss();
aQuery.id(R.id.extra).progress(dialog).image(questionAnsList.get(quetionNumber).url, true, true);
ansOptionInitialize();
}
/*Quation ans intialize and set*/
private void ansOptionInitialize() {
try {
Collections.shuffle(questionAnsbean1.ansOptionList);
gameActivityButton1.setText(questionAnsbean1.ansOptionList.get(0).answer);
gameActivityButton2.setText(questionAnsbean1.ansOptionList.get(1).answer);
gameActivityButton3.setText(questionAnsbean1.ansOptionList.get(2).answer);
gameActivityButton4.setText(questionAnsbean1.ansOptionList.get(3).answer);
if(questionAnsbean1.ansOptionList.get(0).result == 1)
{
trueAns = questionAnsbean1.ansOptionList.get(0).answer;
}
else if(questionAnsbean1.ansOptionList.get(1).result == 1)
{
trueAns = questionAnsbean1.ansOptionList.get(1).answer;
}
else if(questionAnsbean1.ansOptionList.get(2).result == 1)
{
trueAns = questionAnsbean1.ansOptionList.get(2).answer;
}
else if(questionAnsbean1.ansOptionList.get(3).result == 1)
{
trueAns = questionAnsbean1.ansOptionList.get(3).answer;
}
}
catch (Exception e)
{
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.gameActivityButton1:
checkAns(gameActivityButton1.getText().toString());
break;
case R.id.gameActivityButton2:
checkAns(gameActivityButton2.getText().toString());
break;
case R.id.gameActivityButton3:
checkAns(gameActivityButton3.getText().toString());
break;
case R.id.gameActivityButton4:
checkAns(gameActivityButton4.getText().toString());
break;
default:
break;
}
}
private void checkAns(String text) {
BeanEachQuetionScore beanEachQuetionScore = new BeanEachQuetionScore();
beanEachQuetionScore.quetionNo = quetionNumber;
beanEachQuetionScore.url = questionAnsList.get(quetionNumber).url;
beanEachQuetionScore.playerAns = text;
beanEachQuetionScore.trueAns = trueAns;
beanEachQuetionScore.quetionScore = Double.parseDouble(percentageView.getText().toString());
scoreList.add(beanEachQuetionScore);
if (text.equals(trueAns)) {
totalScore = totalScore + Float.parseFloat(percentageView.getText().toString());
textViewTotalScore.setText(String.format("%.2f", totalScore));
quetionNumber++;
if(quetionNumber < questionAnsList.size()) {
quetionInitialize();
}
else {
gameOver();
}
}
else {
totalScore = totalScore - Float.parseFloat(percentageView.getText().toString());
textViewTotalScore.setText(String.format("%.2f", totalScore));
quetionNumber++;
if(quetionNumber < questionAnsList.size()) {
quetionInitialize();
}
else {
gameOver();
}
}
}
private void gameOver() {
session.setScoreBeen(scoreList);
session.setTotalScoreInSession(Float.parseFloat(textViewTotalScore.getText().toString()));
Intent intent = new Intent(getApplicationContext(),ScoreBord.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(getApplicationContext(),SelectCategoryActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
Your issue actually brings up a larger issue that is especially relevant when developing a mobile app: Locale. Rather than use Double.parse(), which does not take Locale into account, consider using NumberFormat instead.
NumberFormat nf = NumberFormat.getInstance(); //gets an instance with the default Locale
Number parsed = nf.parse(percentageView.getText().toString());
beanEachQuetionScore.quetionScore = parsed.doubleValue();
For your float values, you can use the same concept:
Number parsedFloat = nf.parse(someFloatString);
float floatVal = parsedFloat.floatValue();
This of course assumes that OP is in a Locale that uses ',' instead of '.' as a separator.

Why android ViewPager OnTouchListener not called at all

Why my ViewPager OnTouchListener doesn't fire at all !!
Here is my code below:
I'm using ViewPager to automatically slide photos but when i tap on the ViewPager I need to stop the auto sliding but the problem is that my OnTouchListener doesn't fire at all.
JAVA
man_fragment.java
package com.techzone.yallaassouk;
/**
* Created by Yazan on 4/26/2016.
*/
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import com.techzone.yallaassouk.Adapters.Brands_View_Adapter;
import com.techzone.yallaassouk.Adapters.Categories_View_Adapter;
import com.techzone.yallaassouk.Adapters.ImageSlideAdapter;
import com.techzone.yallaassouk.DataItems.Band;
import com.techzone.yallaassouk.DataItems.Brand;
import com.techzone.yallaassouk.DataItems.Category;
import com.techzone.yallaassouk.Utils.CirclePageIndicator;
import com.techzone.yallaassouk.Utils.PageIndicator;
import com.techzone.yallaassouk.Utils.CheckNetworkConnection;
import com.techzone.yallaassouk.json.GetJSONObject;
import com.techzone.yallaassouk.json.JsonReader;
import org.json.JSONObject;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.List;
public class man_fragment extends Fragment {
public static final String ARG_ITEM_ID = "man_fragment";
private static final long ANIM_VIEWPAGER_DELAY = 5000;
private static final long ANIM_VIEWPAGER_DELAY_USER_VIEW = 10000;
private static final int TabNo = 1;
// UI References
ViewPager BandsViewPager;
PageIndicator mIndicator;
RecyclerView brands_Rec_View;
RecyclerView categories_Rec_View;
//lists
List<Band> bands;
List<Brand> brands;
List<Category> categories;
//tasks
RequestBandsTask bands_task;
RequestBrandsTask brands_task;
RequestCategoriesTask categories_task;
AlertDialog alertDialog;
boolean stopSliding = false;
String message;
//lists adapters
Brands_View_Adapter brands_adapter;
Categories_View_Adapter categories_adapter;
//runnables and handlers
private Runnable animateViewPager;
private Handler handler;
//urls
String brandsurl = "http://yazanallahham-001-site1.ftempurl.com/Brands.svc/json/brands/"+TabNo;
String categoriesurl = "http://yazanallahham-001-site1.ftempurl.com/categories.svc/json/categories/"+TabNo+"/0";
String bandsurl = "http://yazanallahham-001-site1.ftempurl.com/bands.svc/json/bands/0";
//activity
FragmentActivity activity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.man_fragment, container, false);
findViewById(rootView);
mIndicator.setOnPageChangeListener(new PageChangeListener());
BandsViewPager.setOnPageChangeListener(new PageChangeListener());
BandsViewPager.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
v.getParent().requestDisallowInterceptTouchEvent(true);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
stopSliding = true;
break;
case MotionEvent.ACTION_CANCEL:
break;
case MotionEvent.ACTION_UP:
// calls when touch release on ViewPager
if (bands != null && bands.size() != 0) {
stopSliding = false;
runnable(bands.size());
handler.postDelayed(animateViewPager,
ANIM_VIEWPAGER_DELAY_USER_VIEW);
}
break;
case MotionEvent.ACTION_MOVE:
// calls when ViewPager touch
if (handler != null && stopSliding == false) {
stopSliding = true;
handler.removeCallbacks(animateViewPager);
}
break;
}
return false;
}
});
// sendRequest();
//init brands recyclerview
brands_Rec_View.setLayoutManager(new LinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false));
brands_Rec_View.addOnItemTouchListener(
new RecyclerItemClickListener(this.getContext(), new RecyclerItemClickListener.OnItemClickListener() {
#Override public void onItemClick(View view, int position) {
categories_fragment nextFrag= new categories_fragment();
Bundle args = new Bundle();
Brand clickedBrand = (Brand)brands.get(position);
args.putInt("BrandId", clickedBrand.getId());
args.putInt("TabId", TabNo);
args.putString("BrandName", clickedBrand.getEnName());
nextFrag.setArguments(args);
getFragmentManager().beginTransaction()
.replace(R.id.main_content, nextFrag, categories_fragment.ARG_ITEM_ID)
.addToBackStack(categories_fragment.ARG_ITEM_ID)
.commit();
}
})
);
//init categories recyclerview
GridLayoutManager LLM = new GridLayoutManager(activity, 2, LinearLayoutManager.VERTICAL, false){
#Override
public boolean canScrollVertically(){
return false;
}
};
categories_Rec_View.setLayoutManager(LLM);
categories_Rec_View.addOnItemTouchListener(
new RecyclerItemClickListener(this.getContext(), new RecyclerItemClickListener.OnItemClickListener() {
#Override public void onItemClick(View view, int position) {
//Log.d("categories","test click" + position);
Items_fragment nextFrag= new Items_fragment();
Bundle args = new Bundle();
Category clickedCategory = (Category)categories.get(position);
args.putInt("CategoryId", clickedCategory.getId());
args.putString("CategoryName", clickedCategory.getEnName());
args.putInt("BrandId", 0);
args.putInt("TabId", TabNo);
nextFrag.setArguments(args);
getFragmentManager().beginTransaction()
.replace(R.id.main_content, nextFrag, Items_fragment.ARG_ITEM_ID)
.addToBackStack(Items_fragment.ARG_ITEM_ID)
.commit();
}
})
);
return rootView;
}
private void findViewById(View view) {
BandsViewPager = (ViewPager) view.findViewById(R.id.man_view_pager);
mIndicator = (CirclePageIndicator) view.findViewById(R.id.indicator);
brands_Rec_View = (RecyclerView) view.findViewById(R.id.brands_RView);
categories_Rec_View = (RecyclerView) view.findViewById(R.id.categories_RView);
}
public void runnable(final int size) {
handler = new Handler();
animateViewPager = new Runnable() {
public void run() {
if (!stopSliding) {
if (BandsViewPager.getCurrentItem() == size - 1) {
BandsViewPager.setCurrentItem(0);
} else {
BandsViewPager.setCurrentItem(
BandsViewPager.getCurrentItem() + 1, true);
}
handler.postDelayed(animateViewPager, ANIM_VIEWPAGER_DELAY);
}
}
};
}
#Override
public void onResume() {
if (bands == null) {
sendRequest();
} else {
BandsViewPager.setAdapter(new ImageSlideAdapter(activity, bands,
man_fragment.this));
mIndicator.setViewPager(BandsViewPager);
runnable(bands.size());
//Re-run callback
handler.postDelayed(animateViewPager, ANIM_VIEWPAGER_DELAY);
}
super.onResume();
}
#Override
public void onPause() {
if (bands_task != null)
bands_task.cancel(true);
if (handler != null) {
//Remove callback
handler.removeCallbacks(animateViewPager);
}
super.onPause();
}
private void sendRequest() {
if (CheckNetworkConnection.isConnectionAvailable(activity)) {
bands_task = new RequestBandsTask(activity);
bands_task.execute(bandsurl);
brands_task = new RequestBrandsTask(activity);
brands_task.execute(brandsurl);
categories_task = new RequestCategoriesTask(activity);
categories_task.execute(categoriesurl);
} else {
message = getResources().getString(R.string.no_internet_connection);
showAlertDialog(message, true);
}
}
public void showAlertDialog(String message, final boolean finish) {
alertDialog = new AlertDialog.Builder(activity).create();
alertDialog.setMessage(message);
alertDialog.setCancelable(false);
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (finish)
activity.finish();
}
});
alertDialog.show();
}
private class PageChangeListener implements ViewPager.OnPageChangeListener {
#Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_IDLE) {
if (bands != null) {
}
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int arg0) {
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
private class RequestBandsTask extends AsyncTask<String, Void, List<Band>> {
private final WeakReference<Activity> activityWeakRef;
Throwable error;
public RequestBandsTask(Activity context) {
this.activityWeakRef = new WeakReference<Activity>(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<Band> doInBackground(String... urls) {
try {
JSONObject jsonObject = getJsonObject(urls[0]);
if (jsonObject != null) {
// JSONObject jsonData = jsonObject
// .getJSONObject(TagName.TAG_BRANDS);
// if (jsonObject != null) {
bands = JsonReader.getBands(jsonObject);
// } else {
// message = jsonObject.getString(TagName.TAG_BRANDS);
// }
}
} catch (Exception e) {
e.printStackTrace();
}
return bands;
}
/**
* It returns jsonObject for the specified url.
*
* #param url
* #return JSONObject
*/
public JSONObject getJsonObject(String url) {
JSONObject jsonObject = null;
try {
jsonObject = GetJSONObject.getJSONObject(url);
} catch (Exception e) {
}
return jsonObject;
}
#Override
protected void onPostExecute(List<Band> result) {
super.onPostExecute(result);
if (activityWeakRef != null && !activityWeakRef.get().isFinishing()) {
if (error != null && error instanceof IOException) {
message = getResources().getString(R.string.time_out);
showAlertDialog(message, true);
} else if (error != null) {
message = getResources().getString(R.string.error_occured);
showAlertDialog(message, true);
} else {
bands = result;
if (result != null) {
if (bands != null && bands.size() != 0) {
//for brands_adapter
BandsViewPager.setAdapter(new ImageSlideAdapter(
activity, bands, man_fragment.this));
mIndicator.setViewPager(BandsViewPager);
runnable(bands.size());
handler.postDelayed(animateViewPager,
ANIM_VIEWPAGER_DELAY);
} else {
}
} else {
}
}
}
}
}
private class RequestBrandsTask extends AsyncTask<String, Void, List<Brand>> {
private final WeakReference<Activity> activityWeakRef;
Throwable error;
public RequestBrandsTask(Activity context) {
this.activityWeakRef = new WeakReference<Activity>(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<Brand> doInBackground(String... urls) {
try {
JSONObject jsonObject = getJsonObject(urls[0]);
if (jsonObject != null) {
// JSONObject jsonData = jsonObject
// .getJSONObject(TagName.TAG_BRANDS);
// if (jsonObject != null) {
brands = JsonReader.getBrands(jsonObject);
// } else {
// message = jsonObject.getString(TagName.TAG_BRANDS);
// }
}
} catch (Exception e) {
e.printStackTrace();
}
return brands;
}
/**
* It returns jsonObject for the specified url.
*
* #param url
* #return JSONObject
*/
public JSONObject getJsonObject(String url) {
JSONObject jsonObject = null;
try {
jsonObject = GetJSONObject.getJSONObject(url);
} catch (Exception e) {
}
return jsonObject;
}
#Override
protected void onPostExecute(List<Brand> result) {
super.onPostExecute(result);
if (activityWeakRef != null && !activityWeakRef.get().isFinishing()) {
if (error != null && error instanceof IOException) {
message = getResources().getString(R.string.time_out);
showAlertDialog(message, true);
} else if (error != null) {
message = getResources().getString(R.string.error_occured);
showAlertDialog(message, true);
} else {
brands = result;
if (result != null) {
if (brands != null && brands.size() != 0) {
//for brands_adapter
brands_adapter = new Brands_View_Adapter(brands);
brands_Rec_View.setAdapter(brands_adapter);// set adapter on recyclerview
} else {
}
} else {
}
}
}
}
}
private class RequestCategoriesTask extends AsyncTask<String, Void, List<Category>> {
private final WeakReference<Activity> activityWeakRef;
Throwable error;
public RequestCategoriesTask(Activity context) {
this.activityWeakRef = new WeakReference<Activity>(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<Category> doInBackground(String... urls) {
try {
JSONObject jsonObject = getJsonObject(urls[0]);
if (jsonObject != null) {
// JSONObject jsonData = jsonObject
// .getJSONObject(TagName.TAG_BRANDS);
// if (jsonObject != null) {
categories = JsonReader.getCategories(jsonObject);
// } else {
// message = jsonObject.getString(TagName.TAG_BRANDS);
// }
}
} catch (Exception e) {
e.printStackTrace();
}
return categories;
}
/**
* It returns jsonObject for the specified url.
*
* #param url
* #return JSONObject
*/
public JSONObject getJsonObject(String url) {
JSONObject jsonObject = null;
try {
jsonObject = GetJSONObject.getJSONObject(url);
} catch (Exception e) {
}
return jsonObject;
}
#Override
protected void onPostExecute(List<Category> result) {
super.onPostExecute(result);
if (activityWeakRef != null && !activityWeakRef.get().isFinishing()) {
if (error != null && error instanceof IOException) {
message = getResources().getString(R.string.time_out);
showAlertDialog(message, true);
} else if (error != null) {
message = getResources().getString(R.string.error_occured);
showAlertDialog(message, true);
} else {
categories = result;
if (result != null) {
if (categories != null && categories.size() != 0) {
//for brands_adapter
categories_adapter = new Categories_View_Adapter(categories);
categories_Rec_View.setAdapter(categories_adapter);// set adapter on recyclerview
categories_Rec_View.getLayoutParams().height = (188*(categories_adapter.getItemCount()+1)+328);
} else {
}
} else {
}
}
}
}
}
}
View Pager Adapter
ImageSlideAdapter.java
package com.techzone.yallaassouk.Adapters;
/**
* Created by Yazan on 5/1/2016.
*/
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.MotionEvent;
import android.view.ViewParent;
import android.widget.ImageView;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import android.app.Activity;
import android.graphics.Bitmap;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import com.techzone.yallaassouk.DataItems.Band;
import com.techzone.yallaassouk.R;
import com.techzone.yallaassouk.TouchImageView;
import com.techzone.yallaassouk.fragment.ProductDetailFragment;
import com.techzone.yallaassouk.man_fragment;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
public class ImageSlideAdapter extends PagerAdapter {
ImageLoader imageLoader = ImageLoader.getInstance();
DisplayImageOptions options;
private ImageLoadingListener imageListener;
FragmentActivity activity;
List<Band> bands;
Fragment homeFragment;
public ImageSlideAdapter(FragmentActivity activity, List<Band> bands,
Fragment homeFragment) {
this.activity = activity;
this.homeFragment = homeFragment;
this.bands = bands;
options = new DisplayImageOptions.Builder()
.showImageOnFail(R.drawable.a1)
.showStubImage(R.drawable.a2)
.showImageForEmptyUri(R.drawable.a3).cacheInMemory()
.cacheOnDisc().build();
imageListener = new ImageDisplayListener();
}
#Override
public int getCount() {
return bands.size();
}
#Override
public View instantiateItem(ViewGroup container, final int position) {
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.vp_image, container, false);
ImageView mImageView = (ImageView) view
.findViewById(R.id.image_display);
imageLoader.displayImage(
((Band) bands.get(position)).getImageURL(), mImageView,
options, imageListener);
container.addView(view);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
private static class ImageDisplayListener extends
SimpleImageLoadingListener {
static final List<String> displayedImages = Collections
.synchronizedList(new LinkedList<String>());
#Override
public void onLoadingComplete(String imageUri, View view,
Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
}
Sorry for being not formatted. I'm new here
I found what was causing the 'ViewPager' not to fire 'OnTouchListener'
In layout XML file :
<com.techzone.yallaassouk.ExtendedViewPager
android:id="#+id/man_view_pager"
android:layout_width="fill_parent"
android:layout_height="137dp" />
<com.techzone.yallaassouk.Utils.CirclePageIndicator
android:id="#+id/indicator"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingTop="130dp"/>
the problem was the 'paddingTop' of the 'CirclePageIndicator' it was set to '130dp' which covers the 'ViewPager' and it was receiving the touch events instead of 'ViewPager' itself.
Thank you.

Categories

Resources