mTabHost = getTabHost();
mTabHost.addTab(mTabHost.newTabSpec(TAB_NEWS).setIndicator(TAB_NEWS).setContent(new Intent(this, NewsActivity1.class)));
mTabHost.addTab(mTabHost.newTabSpec(TAB_BBS).setIndicator(TAB_BBS).setContent(new Intent(this, BBSActivity.class)));
mTabHost.addTab(mTabHost.newTabSpec(TAB_CATEGORY).setIndicator(TAB_CATEGORY).setContent(new Intent(this, CategoryActivity.class)));
mTabHost.addTab(mTabHost.newTabSpec(TAB_DISCOVER).setIndicator(TAB_DISCOVER).setContent(new Intent(this, DiscoverActivity.class)));
mTabHost.addTab(mTabHost.newTabSpec(TAB_MINE).setIndicator(TAB_MINE).setContent(new Intent(this, MineActivity.class)));
Because a reason, i use the TabActivity, but the system's permission dialog can't show in targetSdk23.
for example: in NewsActivity, BBSActivity,CategoryActivity,DiscoverActivity,MineActivity, all cant show.
please help me, thanks~
for example DiscoverActivity:
public class DiscoverActivity extends BaseActivity implements View.OnClickListener{
private RelativeLayout near, plate, search, rate, oil, two_dimension_code, rl_activity, coupon;
private TextView tvActivityTitle;
private String url;
private LoadDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_discover);
GoogleAnalyticsUtil.doGoogleAnalytics();
initView();
initEvent();
}
private void initView() {
// TODO Auto-generated method stub
near = (RelativeLayout) findViewById(R.id.discover_near);
plate = (RelativeLayout) findViewById(R.id.discover_plate);
search = (RelativeLayout) findViewById(R.id.discover_search);
rate = (RelativeLayout) findViewById(R.id.discover_rate);
oil = (RelativeLayout) findViewById(R.id.discover_oil);
two_dimension_code = (RelativeLayout) findViewById(R.id.rl_twodimension_code);
rl_activity = (RelativeLayout) findViewById(R.id.rl_activity);
coupon = (RelativeLayout) findViewById(R.id.rl_coupon);
tvActivityTitle = (TextView) findViewById(R.id.tv_activity_title);
}
private void initEvent() {
near.setOnClickListener(this);
plate.setOnClickListener(this);
search.setOnClickListener(this);
rate.setOnClickListener(this);
oil.setOnClickListener(this);
two_dimension_code.setOnClickListener(this);
rl_activity.setOnClickListener(this);
coupon.setOnClickListener(this);
}
#Override
public void onClick(View v) {
final Intent intent = new Intent();
switch (v.getId()) {
case R.id.discover_near:
GoogleAnalyticsUtil.doGoogleActionAnalytics(GoogleAnalyticsConstant.ActionEvent.NEARPEOPLE_ACTION);
if (TextUtils.isEmpty(ShareProUtils.getUid(this))) {
intent.setClass(this, LoginActivity.class);
startActivity(intent);
} else {
intent.setClass(this, NearbyActivity.class);
startActivity(intent);
}
break;
case R.id.discover_plate:
intent.setClass(this, ForumActivity.class);
startActivity(intent);
break;
case R.id.discover_search:
intent.setClass(this, TopicSearchActivity.class);
startActivity(intent);
break;
case R.id.discover_rate:
intent.setClass(this, RateActivity.class);
startActivity(intent);
break;
case R.id.discover_oil:
intent.setClass(this, OilActivity.class);
startActivity(intent);
break;
case R.id.rl_twodimension_code:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
DialogUtil.getInstance().showPermissionDialog(this, "permission");
} else {
intent.setClass(DiscoverActivity.this, CaptureActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(intent, 1);
}
} else {
intent.setClass(DiscoverActivity.this, CaptureActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(intent, 1);
}
break;
case R.id.rl_activity:
intent.setClass(this, WebViewActivity.class);
intent.putExtra("url", url);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
break;
case R.id.rl_coupon:
intent.setClass(this, GroupBuyListActivity.class);
startActivity(intent);
break;
}
}
private void loadActivity() {
Map<String, String> mp = new HashMap<String, String>();
Okhttp.getIntance().post(Api.REAL_URL, Api.YORKBBS_CMS_TXTSETTING, mp, new StringCallback() {
#Override
public void onError(Call call, Exception e) {
}
#Override
public void onResponse(String response) {
if (!TextUtils.isEmpty(response)) {
String result = ParamUtils.ConvertData(response);
JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
if (jsonObject.has("list")) {
rl_activity.setVisibility(View.VISIBLE);
String list = jsonObject.get("list").toString();
List<Discoverac> listObj = new Gson().fromJson(list, new TypeToken<List<Discoverac>>() {
}.getType());
if (listObj != null && listObj.size() > 0) {
tvActivityTitle.setText(listObj.get(0).getTxt());
url = listObj.get(0).getUrl();
}
}
}
rl_activity.setVisibility(View.GONE);
}
});
}
private void check(String ticket) {
Map<String, String> mp = new HashMap<String, String>();
mp.put("sessionkey", ShareProUtils.getLoginSession(this));
mp.put("code", ticket);
mp.put("merchantid", ShareProUtils.getUid(this));
Okhttp.getIntance().post(Api.GROUPBUY_URL, Api.GROUPON_CHECK, mp, new StringCallback() {
#Override
public void onBefore(Request request) {
super.onBefore(request);
dialog = DialogUtil.getInstance().showLoadDialog(DiscoverActivity.this, "正在验证...");
}
#Override
public void onError(Call call, Exception e) {
}
#Override
public void onResponse(String response) {
if (!TextUtils.isEmpty(response)) {
String result = ParamUtils.ConvertData(response);
GrouponDetailResponse response1 = new Gson().fromJson(result,GrouponDetailResponse.class);
if (response1.getFlag().equals("0")){
Intent intent = new Intent(DiscoverActivity.this, TicketCheckSuccessActivity.class);
startActivity(intent);
}else {
Intent intent = new Intent(DiscoverActivity.this, TicketCheckFailActivity.class);
startActivity(intent);
}
} else {
TipsToast.show(DiscoverActivity.this, "error");
}
}
#Override
public void onAfter() {
DialogUtil.getInstance().dissMissDialog(dialog);
super.onAfter();
}
});
}
#Override
protected void onResume() {
super.onResume();
if (isNet()) {
loadActivity();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 1) {
Bundle bundle = data.getExtras();
String result = bundle.getString("result");
if (!TextUtils.isEmpty(result)) {
if (result.contains("code")) {
if (TextUtils.isEmpty(ShareProUtils.getUid(this))) {
Intent login = new Intent(this, LoginActivity.class);
startActivity(login);
return;
}
result = result.replaceAll("http://www.yorkbbs.ca\\?yorkbbscode=","");
check(result);
} else {
Intent intent = new Intent(this, WebViewActivity.class);
intent.putExtra("url", result);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
} else {
TipsToast.show(this, "scan error");
}
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// NOTE: delegate the permission handling to generated method
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
return false;
}
}
TabActivity is now deprecated. To Create Tab you have to create it using Fragment and ViewPager.
Here is example to create Tab using Fragment and ViewPager .
see Exmaple here : http://www.truiton.com/2015/06/android-tabs-example-fragments-viewpager/
Related
Hi in the below code displaying the devices near by via bluetooth.
The below code was working fine for every device except one plus 6 phone.
I found a bug in the one plus 6 phone. If we turn on bluetooth and location then list of the near devices are listed.
can any one help me how to reslove the bug especially on one plus phones.
public class DeviceScanActivity extends AppCompatActivity {
private static final String TAG = DeviceScanActivity.class.getSimpleName();
private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
#Bind(R.id.back)
TextView mBack;
#Bind(R.id.refresh)
TextView mRefresh;
#Bind(R.id.toolBar)
Toolbar mToolBar;
#Bind(R.id.scan_status)
TextView mScanStatus;
#Bind(R.id.deviceListView)
RecyclerView mDeviceListView;
#Bind(R.id.scanningProgress)
ProgressBar mScanningProgress;
private DeviceListAdapter mAdapter;
private BleService mBleService;
private List<BluetoothDevice> mBleDevices;
private SharedPreferences mPref;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_device);
ButterKnife.bind(this);
mProgressDialog = new ProgressDialog(this);
mPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
initToolBar();
mBleDevices = new ArrayList<>();
mAdapter = new DeviceListAdapter(this);
mDeviceListView.setAdapter(mAdapter);
LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
mDeviceListView.setLayoutManager(manager);
mDeviceListView.addOnItemTouchListener(new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
showProgressDialog();
List<BluetoothDevice> bluetoothDevices = mAdapter.getBluetoothDevices();
if (bluetoothDevices != null) {
if (bluetoothDevices.size() > position) {
BluetoothDevice bluetoothDevice = bluetoothDevices.get(position);
if (bluetoothDevice != null) {
String address = bluetoothDevice.getAddress();
mBleService.connect(address);
}
}
}
}
}));
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BleService.ACTION_DEVICE_FOUND);
intentFilter.addAction(BleService.ACTION_GATT_CONNECTED);
intentFilter.addAction(BleService.ACTION_GAT_CONNECTING);
intentFilter.addAction(BleService.ACTION_GATT_DISCONNECTED);
intentFilter.addAction(BleService.ACTION_GAT_SERVICE_DISCOVERED);
registerReceiver(mGattUpdateReceiver, intentFilter);
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.BLUETOOTH,Manifest.permission.ACCESS_FINE_LOCATION
, Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
}
} else {
if (mServiceConnection != null) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 101);
}
Intent intent = new Intent(this, BleService.class);
bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
}
}
private void showProgressDialog() {
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialog(this);
}
mProgressDialog.setMessage(getString(R.string.loading));
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
}
private ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
mBleService = ((BleService.LocalBinder) iBinder).getLeService();
if (mBleService != null) {
mBleService.scanLeDevice(true);
mScanStatus.setVisibility(View.VISIBLE);
mScanStatus.setText(R.string.scanning_device);
}
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
}
};
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 101) {
if (mBleService != null) {
mBleService.scanLeDevice(true);
}
}
}
private BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
switch (action) {
case BleService.ACTION_DEVICE_FOUND:
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BleService.EXTRA_DEVICE);
if (mBleDevices != null) {
if (!mBleDevices.contains(device)) {
mBleDevices.add(device);
mAdapter.udpateBluetoothDevices(mBleDevices);
mAdapter.notifyDataSetChanged();
}
}
break;
case BleService.ACTION_GATT_CONNECTED:
Log.d(TAG, "!Action gat connected...");
mBleService.scanLeDevice(false);
mScanStatus.setVisibility(View.VISIBLE);
mScanStatus.setText(getString(R.string.connected));
break;
case BleService.ACTION_GAT_CONNECTING:
mScanStatus.setVisibility(View.VISIBLE);
mScanStatus.setText(getString(R.string.connecting));
Log.d(TAG, "!Action Gat Connecting..");
break;
case BleService.ACTION_GATT_DISCONNECTED:
mScanStatus.setVisibility(View.VISIBLE);
mScanStatus.setText(getString(R.string.disconnected));
mScanningProgress.setVisibility(View.GONE);
mRefresh.setVisibility(View.VISIBLE);
if (mProgressDialog != null) {
mProgressDialog.dismiss();
}
Log.d(TAG, "!Action Gat Disconnected..");
break;
case BleService.ACTION_GAT_SERVICE_DISCOVERED:
boolean isOperator = mPref.getBoolean(Constants.IS_OPERATOR, false);
if (mProgressDialog != null) {
mProgressDialog.dismiss();
}
if (isOperator) {
Intent homeIntent = new Intent(DeviceScanActivity.this, HomeScreenActivity.class);
startActivity(homeIntent);
finish();
} else {
Intent lightControllIntent = new Intent(DeviceScanActivity.this, LightConfigurationActivity.class);
startActivity(lightControllIntent);
finish();
}
mScanStatus.setText(getString(R.string.discoveringService));
Log.d(TAG, "!Action Gat Discovering..");
break;
}
}
};
private void initToolBar() {
mRefresh.setVisibility(View.VISIBLE);
}
#OnClick(R.id.refresh)
public void onClick() {
mScanStatus.setVisibility(View.VISIBLE);
mRefresh.setVisibility(View.GONE);
mScanningProgress.setVisibility(View.VISIBLE);
mBleDevices.clear();
mAdapter.udpateBluetoothDevices(new ArrayList<BluetoothDevice>());
mAdapter.notifyDataSetChanged();
}
#Override
protected void onDestroy() {
if (mServiceConnection != null) {
unbindService(mServiceConnection);
}
if (mGattUpdateReceiver != null) {
unregisterReceiver(mGattUpdateReceiver);
}
super.onDestroy();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_COARSE_LOCATION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (mServiceConnection != null) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 101);
}
Intent intent = new Intent(this, BleService.class);
bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
} else {
finish();
}
}
}
}
I am building an app. One of the features I have is a paid option in which the user has access to an additional layout. Right now, the user can get there by clicking a button. Instead, I would like to have a swiping motion- if the user swipes down, it will ask for permission for the paid layout. If they do pay, when they swipe up, they can access the original layout.
Here is my main activity :
public class MainActivity extends AppCompatActivity {
EditText editText2;
Button btn_purchase;
ImageView imageView2;
String skuId;
SessionManager sessionManager;
// create new Person
private BillingClient mBillingClient;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sessionManager=new SessionManager(MainActivity.this);
if(sessionManager.getPurchased()){
Intent intent = new Intent(MainActivity.this, PaidActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
btn_purchase=findViewById(R.id.btn_purchase);
imageView2 = (ImageView) findViewById(R.id.imageView2);
mBillingClient = BillingClient.newBuilder(MainActivity.this).setListener(new PurchasesUpdatedListener() {
#Override
public void onPurchasesUpdated(int responseCode, #Nullable List<Purchase> purchases) {
if (responseCode == BillingClient.BillingResponse.OK
&& purchases != null) {
for (Purchase purchase : purchases) {
//TODO: Handle purchase
// handlePurchase(purchase);
Log.e("Main", "handle Purchase ");
Log.e("MainAct", "onPurchasesUpdated() response: " + responseCode);
Log.e("dev", "successful purchase...");
String purchasedSku = purchase.getSku();
Log.e("dev", "Purchased SKU: " + purchasedSku);
String purchaseToken = purchase.getPurchaseToken();
sessionManager.savePurchased(true);
Intent intent = new Intent(MainActivity.this, PaidActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
} else if (responseCode == BillingClient.BillingResponse.USER_CANCELED) {
// Handle an error caused by a user cancelling the purchase flow.
} else {
// Handle any other error codes.
}
}
}).build();
List<String> skuList = new ArrayList <> ();
skuList.add("appsubscription2018");
SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();
params.setSkusList(skuList).setType(BillingClient.SkuType.INAPP);
mBillingClient.querySkuDetailsAsync(params.build(),
new SkuDetailsResponseListener() {
#Override
public void onSkuDetailsResponse(int responseCode, List<SkuDetails> skuDetailsList) {
// Process the result.
if (responseCode == BillingClient.BillingResponse.OK && skuDetailsList != null) {
Log.e("MainActivity", "onSkuDetailsResponse: success");
for (SkuDetails skuDetails : skuDetailsList) {
Log.e("MainActivity", "products: "+skuDetailsList);
String sku = skuDetails.getSku();
skuId = skuDetails.getSku();
String price = skuDetails.getPrice();
if ("appsubscription2018 ".equals(sku)) {
Log.e("MainActivity", "product is appsubscription2018 ");
// mPremiumUpgradePrice = price;
}
}
}
}
});
btn_purchase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mBillingClient.startConnection(new BillingClientStateListener() {
#Override
public void onBillingSetupFinished(#BillingClient.BillingResponse int billingResponseCode) {
if (billingResponseCode == BillingClient.BillingResponse.OK) {
// The billing client is ready. You can query purchases here.
// The billing client is ready. You can query purchases here.
BillingFlowParams flowParams = BillingFlowParams.newBuilder()
.setSku("appsubscription2018")
.setType(BillingClient.SkuType.INAPP)
.build();
int responseCode = mBillingClient.launchBillingFlow(MainActivity.this, flowParams);
if (responseCode != BillingClient.BillingResponse.OK) {
Log.e("Main", "launchBillingFlow ok");
}
}
}
#Override
public void onBillingServiceDisconnected() {
// Try to restart the connection on the next request to
// Google Play by calling the startConnection() method.
}
});
}
});
imageView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (checkFilePermission(MainActivity.this)){
getPhoto();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode ==1 && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
imageView2.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static boolean checkFilePermission(final Context context) {
int currentAPIVersion = Build.VERSION.SDK_INT;
if(currentAPIVersion>= Build.VERSION_CODES.M)
{
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("External storage permission is necessary");
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
} else {
ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
public void getPhoto() {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent,1);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode ==1){
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED);{
getPhoto();
}
}
}
}
I am new to android development , my app is ready but on some devices it lags when opening the navigation drawer and somethings on onclick event.I tried to use threads so that each event occurs on new thread but still i see lag please help me with this.
public class MainActivity extends BaseActivity implements OnClickListener {
private Button scanBtn,scanBtn2,scanBtn3;
Animation animTranslate,animAlpha;
LinearLayout lv;
Handler handler;
String[] permissions;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_base);
super.onCreate(savedInstanceState);
permissions = new String[3];
permissions[0] = Manifest.permission.WRITE_EXTERNAL_STORAGE;
permissions[1] = Manifest.permission.READ_EXTERNAL_STORAGE;
permissions[2]=Manifest.permission.CAMERA;
ActivityCompat.requestPermissions(
this,
permissions,
5
);
scanBtn = (Button)findViewById(R.id.scanner);
scanBtn2=(Button)findViewById(R.id.scanner2);
scanBtn3=(Button)findViewById(R.id.scanner3);
lv=(LinearLayout)findViewById(R.id.container);
animTranslate= AnimationUtils.loadAnimation(MainActivity.this,R.anim.anim_translate);
animAlpha=AnimationUtils.loadAnimation(MainActivity.this,R.anim.anim_alpha);
scanBtn.setOnClickListener(MainActivity.this);
scanBtn2.setOnClickListener(MainActivity.this);
scanBtn3.setOnClickListener(MainActivity.this);
}
public void onClick(View v){
if(v.getId()==R.id.scanner){
v.startAnimation(animTranslate);
lv.startAnimation(animAlpha);
final IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.setDesiredBarcodeFormats(IntentIntegrator.QR_CODE_TYPES);
scanIntegrator.setPrompt(" ");
scanIntegrator.setCameraId(0);
scanIntegrator.setBeepEnabled(true);
scanIntegrator.setBarcodeImageEnabled(false);
handler=new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
scanIntegrator.initiateScan();
}
},500);
}else if(v.getId()==R.id.scanner2){
v.startAnimation(animTranslate);
lv.startAnimation(animAlpha);
final IntentIntegrator scanIntegrator2=new IntentIntegrator(this);
scanIntegrator2.setDesiredBarcodeFormats(IntentIntegrator.ONE_D_CODE_TYPES);
scanIntegrator2.setPrompt(" ");
scanIntegrator2.setCameraId(0);
scanIntegrator2.setBeepEnabled(true);
scanIntegrator2.setBarcodeImageEnabled(true);
handler=new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
scanIntegrator2.initiateScan();
}
},500);
}else if(v.getId()==R.id.scanner3){
v.startAnimation(animTranslate);
lv.startAnimation(animAlpha);
final Intent intent=new Intent(this,GenerateQRCodeActivity.class);
handler=new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
startActivity(intent); overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
}
},500);
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
String scanContent = scanningResult.getContents();
String scanFormat = scanningResult.getFormatName();
Intent intent1=new Intent(this,ResultActivity.class);
intent1.putExtra("con",scanContent);
if(scanContent != null && scanFormat != null) {
startActivity(intent1);
}
}
else{
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent e) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
// your action...
if (!mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.openDrawer(mDrawerList);
}
else{
mDrawerLayout.closeDrawer(mDrawerList);
}
return true;
}
return super.onKeyDown(keyCode, e);
}
#Override
public void onBackPressed() {
if(mDrawerLayout.isDrawerOpen(mDrawerList)){
mDrawerLayout.closeDrawer(mDrawerList);
}
else{
finish();
}
}
}
Another class calls the GridView class below that is populated with images from a parse server, if a user clicks on a grid item, it starts the same GridView class with different bundled strings so it can pull from a different parse database class. Now at this point, when a user clicks an GridView item (from the 2nd gridview that was set up), I want it to start a different activity class.
I tried doing an if/else if statement in the onItemClick that takes the "PARSE_CLASS" bundled string but I can't seem to get that to work. I'm relatively new to android programming so I don't know the best way to do this.
public class DisplayGrid extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
GridView gridView = null;
List<ParseObject> obj;
ProgressDialog loadProgress;
GridViewAdapter adapter;
Bundle extras = new Bundle();
GridViewAdapter itemGridAdapter;
private List<ImageList> imageArrayList = null;
private List<String> categoryNameArrayList = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ws_display_grid);
imageArrayList = new ArrayList<ImageList>();
categoryNameArrayList = new ArrayList<String>();
gridView = (GridView) findViewById(R.id.gridView);
itemGridAdapter = new GridViewAdapter(DisplayGrid.this, imageArrayList);
gridView.setAdapter(itemGridAdapter);
new RemoteDataTask().execute();
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
Intent i = getIntent();
Bundle itemExtras = i.getExtras();
final String activeSupplier = itemExtras.getString("SUPPLIER");
String parseClass = extras.getString("PARSE_CLASS");
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
Intent t = new Intent(getApplicationContext(), DisplayGrid.class);
extras.putString("SUPPLIER", activeSupplier);
extras.putString("PARSE_CLASS", "Items");
t.putExtras(extras);
startActivity(t);
}
});
}//end onCreate method
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
//RemoteDataTask
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
loadProgress = new ProgressDialog(DisplayGrid.this);
loadProgress.setTitle("Images");
loadProgress.setMessage("Loading...");
loadProgress.setIndeterminate(false);
loadProgress.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
Intent i = getIntent();
Bundle extras = i.getExtras();
String parseClass = extras.getString("PARSE_CLASS");
String activeSupplier = extras.getString("SUPPLIER");
String category;
ParseQuery<ParseObject> query = new ParseQuery<>(parseClass);
query.whereEqualTo("username", activeSupplier);
obj = query.find();
if (parseClass == "Items") {
category = extras.getString("CATEGORY");
query.whereEqualTo("category", category);
}
for (ParseObject categories : obj) {
//get image
ParseFile image = (ParseFile) categories.get("image");
ImageList gridBlock = new ImageList();
gridBlock.setImage(image.getUrl());
imageArrayList.add(gridBlock);
Log.i("AppInfo", "image sent to imageArrayList");
String categoryName = null;
//get category name
if (categoryName == null) {
} else {
categoryName = categories.getString("categoryName");
categoryNameArrayList.add(categoryName);
Log.i("AppInfo", categoryName);
}
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
gridView = (GridView) findViewById(R.id.gridView);
adapter = new GridViewAdapter(DisplayGrid.this, imageArrayList);
gridView.setAdapter(adapter);
loadProgress.dismiss();
Log.i("AppInfo", "CategoryGrid Populated");
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
try {
Bitmap bitmapImage =
MediaStore.Images.Media.getBitmap
(this.getContentResolver(), selectedImage);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
//convert to parse file
ParseFile file = new ParseFile("Img.png", byteArray);
ParseObject object = new ParseObject("Categories");
object.put("username", ParseUser.getCurrentUser().getUsername());
object.put("image", file);
object.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast.makeText(getApplication().getBaseContext(), "Your image has been saved", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplication().getBaseContext(), "Upload failed, please try again", Toast.LENGTH_SHORT).show();
}
}
});
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplication().getBaseContext(), "Upload failed, please try again", Toast.LENGTH_SHORT).show();
}
}
}
//begin getTitle method
//begin createMenu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(getApplication())
.inflate(R.menu.options, menu);
return (super.onCreateOptionsMenu(menu));
}
//end createMenu
//begin onOptionsItemSelected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.manufacturers) {
Intent i = new Intent(getApplicationContext(), SupplierList.class);
startActivity(i);
return true;
} else if (item.getItemId() == R.id.add) {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 1);
return true;
} else if (item.getItemId() == R.id.sign_out) {
ParseUser.logOut();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
return true;
}
return (super.onOptionsItemSelected(item));
}
//end onOptionsItemSelected
}
This is what I tried. When I tried this, the second GridView wouldn't load. So I'm guessing I'm unable to retrieve the "PARSE_CLASS" bundled string the second time around.
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
Intent i = getIntent();
Bundle itemExtras = i.getExtras();
final String activeSupplier = itemExtras.getString("SUPPLIER");
String parseClass = extras.getString("PARSE_CLASS");
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
if (parseClass == "Categories") {
Intent t = new Intent(getApplicationContext(), DisplayGrid.class);
extras.putString("SUPPLIER", activeSupplier);
extras.putString("PARSE_CLASS", "Items");
t.putExtras(extras);
startActivity(t);
} else if(parseClass == "Items"){
Intent t = new Intent(getApplicationContext(), ItemDisplay.class);
//extras.putString("SUPPLIER", activeSupplier);
//extras.putString("PARSE_CLASS", "Items");
//t.putExtras(extras);
startActivity(t);
}
}
});
ANSWER
Someone on reddit's learn programming was nice enough to point out that I had an issue with string comparisons. had to use
if(parseClass.equals("Categories")){}
instead of
if(parseClass == "Categories"){}
I feel like an idiot, hopefully someone else benefits from this long disastrous effort.
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
Intent t = getIntent();
Bundle itemExtras = t.getExtras();
String activeSupplier = itemExtras.getString("SUPPLIER");
String parseClass = itemExtras.getString("PARSE_CLASS");
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
Log.i("AppInfo", parseClass);
if (parseClass.equals("Categories")) {
Log.i("AppInfo", parseClass);
Intent t = new Intent(getApplicationContext(), DisplayGrid.class);
String categoryName = categoryNameArrayList.get(position);
itemExtras.putString("SUPPLIER", activeSupplier);
itemExtras.putString("PARSE_CLASS", "Items");
itemExtras.putString("CATEGORY_NAME", categoryName);
t.putExtras(itemExtras);
startActivity(t);
} else if (parseClass.equals("Items")) {
Intent t = new Intent(getApplicationContext(), ItemDisplay.class);
//extras.putString("SUPPLIER", activeSupplier);
//extras.putString("PARSE_CLASS", "Items");
//t.putExtras(extras);
startActivity(t);
}
}
});
public class DisplayGrid extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
GridView gridView = null;
List<ParseObject> obj;
ProgressDialog loadProgress;
GridViewAdapter adapter;
Bundle extras = new Bundle();
GridViewAdapter itemGridAdapter;
private List<ImageList> imageArrayList = null;
private List<String> categoryNameArrayList = null;
String activeSupplier;
String parseClass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ws_display_grid);
imageArrayList = new ArrayList<ImageList>();
categoryNameArrayList = new ArrayList<String>();
Intent i = getIntent();
if (null != i) {
Bundle itemExtras = i.getExtras();
activeSupplier = itemExtras.getString("SUPPLIER");
parseClass = itemExtras.getString("PARSE_CLASS");
}
RemoteDataTask remoteDataAsync = new RemoteDataTask();
remoteDataAsync.execute();
if(remoteDataAsync.getStatus() == AsyncTask.Status.PENDING){
// My AsyncTask has not started yet
}
if(remoteDataAsync.getStatus() == AsyncTask.Status.RUNNING){
// My AsyncTask is currently doing work in doInBackground()
}
if(remoteDataAsync.getStatus() == AsyncTask.Status.FINISHED){
// My AsyncTask is done and onPostExecute was called
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
Intent t = new Intent(getApplicationContext(), DisplayGrid.class);
extras.putString("SUPPLIER", activeSupplier);
extras.putString("PARSE_CLASS", parseClass);
t.putExtras(extras);
startActivity(t);
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
//RemoteDataTask
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
loadProgress = new ProgressDialog(DisplayGrid.this);
loadProgress.setTitle("Images");
loadProgress.setMessage("Loading...");
loadProgress.setIndeterminate(false);
loadProgress.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
Intent i = getIntent();
Bundle extras = i.getExtras();
String parseClass = extras.getString("PARSE_CLASS");
String activeSupplier = extras.getString("SUPPLIER");
String category;
ParseQuery<ParseObject> query = new ParseQuery<>(parseClass);
query.whereEqualTo("username", activeSupplier);
obj = query.find();
if (parseClass == "Items") {
category = extras.getString("CATEGORY");
query.whereEqualTo("category", category);
}
for (ParseObject categories : obj) {
//get image
ParseFile image = (ParseFile) categories.get("image");
ImageList gridBlock = new ImageList();
gridBlock.setImage(image.getUrl());
imageArrayList.add(gridBlock);
Log.i("AppInfo", "image sent to imageArrayList");
String categoryName = null;
//get category name
if (categoryName == null) {
} else {
categoryName = categories.getString("categoryName");
categoryNameArrayList.add(categoryName);
Log.i("AppInfo", categoryName);
}
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
adapter = new GridViewAdapter(DisplayGrid.this, imageArrayList);
gridView.setAdapter(adapter);
loadProgress.dismiss();
Log.i("AppInfo", "CategoryGrid Populated");
}//end onCreate method
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
try {
Bitmap bitmapImage =
MediaStore.Images.Media.getBitmap
(this.getContentResolver(), selectedImage);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
//convert to parse file
ParseFile file = new ParseFile("Img.png", byteArray);
ParseObject object = new ParseObject("Categories");
object.put("username", ParseUser.getCurrentUser().getUsername());
object.put("image", file);
object.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast.makeText(getApplication().getBaseContext(), "Your image has been saved", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplication().getBaseContext(), "Upload failed, please try again", Toast.LENGTH_SHORT).show();
}
}
});
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplication().getBaseContext(), "Upload failed, please try again", Toast.LENGTH_SHORT).show();
}
}
}
//begin getTitle method
//begin createMenu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(getApplication())
.inflate(R.menu.options, menu);
return (super.onCreateOptionsMenu(menu));
}
//end createMenu
//begin onOptionsItemSelected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.manufacturers) {
Intent i = new Intent(getApplicationContext(), SupplierList.class);
startActivity(i);
return true;
} else if (item.getItemId() == R.id.add) {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 1);
return true;
} else if (item.getItemId() == R.id.sign_out) {
ParseUser.logOut();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
return true;
}
return (super.onOptionsItemSelected(item));
}
//end onOptionsItemSelected
}
i have a problem to send fbid to my server after logged out once. and if i want to login again it always send twice request and start the activity twice.
MainActivity.java:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("TheGaffer", "ONCREATE");
mFacebook = new Facebook(APP_ID);
SessionStore.restore(mFacebook, this);
setContentView(R.layout.login_view);
mLoginButton = (LoginButton) findViewById(R.id.login);
SessionEvents.addAuthListener(new SampleAuthListener());
mLoginButton.init(this, mFacebook);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
mFacebook.authorizeCallback(requestCode, resultCode, data);
}
public class SampleAuthListener implements AuthListener {
public void onAuthSucceed() {
new fbRequest().execute("/user_profiles/registerUser");
}
private class fbRequest extends AsyncTask<String, Void, String> {
protected void onPreExecute() {
progressDialog = ProgressDialog.show(TheGaffer.this , null,
"Loading...");
}
protected String doInBackground(String... urls) {
String fbid = null;
Bundle params = new Bundle();
params.putString("fields", "id,name");
try {
JSONObject jsonObjSend = new JSONObject();
JSONObject fbData = new JSONObject(mFacebook.request("me", params));
fbid = fbData.getString("id");
jsonObjSend.put("fbid", fbData.getString("id"));
jsonObjSend.put("username", fbData.getString("name"));
jsonObjSend.put("playerPhoto", "http://graph.facebook.com/"+ fbData.getString("id") +"/picture");
HttpClient.SendHttpPost(urls[0], jsonObjSend);
} catch (Exception e) {
Log.e("FACEBOOK", "Error parsing data " + e.toString());
}
return fbid;
}
#Override
protected void onPostExecute(String fbid) {
Toast.makeText(getApplicationContext(), "Login successful", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
Intent intent = new Intent(TheGaffer.this, TeamActivity.class);
intent.putExtra("fbid", fbid);
startActivity(intent);
}
}
TeamActivity.java:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_create_team:
intent = new Intent(TeamActivity.this, CreateTeam.class);
return true;
case R.id.menu_logout:
Log.i("Logout", "Logged out");
Intent intent = new Intent(TeamActivity.this, TheGaffer.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Once I was trapped in similar situation where Activity call twice one after another.
To avoid this after lots of research I find a very easy solution.
May be solution is not perfect but works for me
in manifest.xml file
in your activity just add
android:launchMode="singleTask"