Bluetooth Printer Connection Failed in Android - java

I want to make a POS app. In this app, I need to print a receipt, but I have a problem with the bluetooth connection.
In this code, I want to set the printer device that I use in my fragment. I want the bluetooth to stay connected even though I move to another fragment. I put the code in my MainActivity, but the problem is every time I move to another fragment, mService is always null. So I couldn't connect to the device.
Please help me. Thanks in advance.
MainActivity.Java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener{
private static final String TAG = "MainActivity";
Fragment fragment = null;
Class fragmentClass = null;
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
public static final int MESSAGE_CONNECTION_LOST = 6;
public static final int MESSAGE_UNABLE_CONNECT = 7;
private String mConnectedDeviceName = null;
// Key names received from the BluetoothService Handler
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
public static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
private BluetoothAdapter mBluetoothAdapter = null;
public BluetoothService mService = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
fragmentClass = RegisterFragment.class;
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_main2, fragment).commit();
Log.v(TAG, "Starting DoDaily service...");
startService(new Intent(this, DoDaily.class));
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
FragmentManager fm = getSupportFragmentManager();
//if you added fragment via layout xml
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the session
} else {
if (mService == null) {
setMService();
}
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.main2, menu);
return true;
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
String TAG_FRAGMENT="";
if (id == R.id.nav_regist) {
fragmentClass = RegisterFragment.class;
TAG_FRAGMENT ="register";
// Handle the camera action
} else if (id == R.id.nav_activity) {
fragmentClass = ActivityFragment.class;
TAG_FRAGMENT ="activity";
}
else if(id == R.id.nav_inventory)
{
fragmentClass = InventoryFragment.class;
TAG_FRAGMENT ="inventory";
}
else if (id == R.id.nav_manage) {
fragmentClass = SettingFragment.class;
TAG_FRAGMENT ="setting";
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_main2, fragment,TAG_FRAGMENT).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#SuppressLint("HandlerLeak")
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
if (DEBUG)
Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case BluetoothService.STATE_CONNECTED:
//btnScan.setText(getText(R.string.Connecting));
fragment1.btnScanEnable(false);
break;
case BluetoothService.STATE_CONNECTING:
Toast.makeText(MainActivity.this,R.string.title_connecting,Toast.LENGTH_SHORT).show();
break;
case BluetoothService.STATE_LISTEN:
case BluetoothService.STATE_NONE:
Toast.makeText(MainActivity.this,R.string.title_not_connected,Toast.LENGTH_SHORT).show();
break;
}
break;
case MESSAGE_WRITE:
break;
case MESSAGE_READ:
break;
case MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
Toast.makeText(MainActivity.this,"Connected to " + mConnectedDeviceName,
Toast.LENGTH_SHORT).show();
String text ="Connected to "+mConnectedDeviceName;
fragment1.setTvText(text);
break;
case MESSAGE_TOAST:
Toast.makeText(MainActivity.this, msg.getData().getString(TOAST), Toast.LENGTH_SHORT).show();
break;
case MESSAGE_CONNECTION_LOST:
Toast.makeText(MainActivity.this, "Device connection was lost",Toast.LENGTH_SHORT).show();
String text1 ="Not Connect to Any Device";
fragment1.setTvText(text1);
// editText.setEnabled(false);
// sendButton.setEnabled(false);
break;
case MESSAGE_UNABLE_CONNECT:
Toast.makeText(MainActivity.this, "Unable to connect device",
Toast.LENGTH_SHORT).show();
break;
}
}
};
#Override
public void onStart() {
super.onStart();
// If Bluetooth is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the session
} else {
if (mService == null){
setMService();
}
}
}
#Override
public synchronized void onResume() {
super.onResume();
if (mService != null) {
if (mService.getState() == BluetoothService.STATE_NONE) {
// Start the Bluetooth services
mService.start();
}
}
}
#Override
public synchronized void onPause() {
super.onPause();
if (DEBUG)
Log.e(TAG, "- ON PAUSE -");
}
#Override
public void onStop() {
super.onStop();
if (DEBUG)
Log.e(TAG, "-- ON STOP --");
}
#Override
public void onDestroy() {
super.onDestroy();
// Stop the Bluetooth services
if (mService != null)
mService.stop();
if (DEBUG)
Log.e(TAG, "--- ON DESTROY ---");
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (DEBUG)
Log.d(TAG, "onActivityResult " + resultCode);
switch (requestCode) {
case REQUEST_CONNECT_DEVICE:{
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
// Get the device MAC address
String address = data.getExtras().getString(
DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BLuetoothDevice object
if (BluetoothAdapter.checkBluetoothAddress(address)) {
BluetoothDevice device = mBluetoothAdapter
.getRemoteDevice(address);
// Attempt to connect to the device
mService.connect(device);
}
}
break;
}
case REQUEST_ENABLE_BT:{
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a session
// FragmentManager fm1 = getSupportFragmentManager();
// SettingFragment fragment1 = (SettingFragment) fm1.findFragmentByTag("setting");
// fragment1.KeyListenerInit();
setMService();
} else {
// User did not enable Bluetooth or an error occured
Log.d(TAG, "BT not enabled");
Toast.makeText(MainActivity.this, R.string.bt_not_enabled_leaving,Toast.LENGTH_SHORT).show();
onBackPressed();
}
break;
}
}
}
public void setMService()
{
mService = new BluetoothService(MainActivity.this, mHandler);
}
}
SettingFragment.Java
public class SettingFragment extends Fragment {
public static final int REQUEST_CONNECT_DEVICE = 1;
private static final String CHINESE = "GBK";
SessionManagement sessionManagement;
DatabaseHandler db;
TextView tvConnected;
Button btnScan;
Button btnTest;
public SettingFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootview = inflater.inflate(R.layout.fragment_setting, container, false);
getActivity().setTitle("Setting");
btnScan = (Button)rootview.findViewById(R.id.btnScan);
btnTest = (Button) rootview.findViewById(R.id.btnTest);
tvConnected = (TextView) rootview.findViewById(R.id.tvPrinterConnect);
KeyListenerInit();
return rootview;
}
public void setTvText(String text)
{
tvConnected = (TextView) getActivity().findViewById(R.id.tvPrinterConnect);
tvConnected.setText(text);
}
public void btnScanEnable(Boolean set)
{
btnScan = (Button)getActivity().findViewById(R.id.btnScan);
btnScan.setEnabled(set);
}
public void KeyListenerInit() {
btnScan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent serverIntent = new Intent(getActivity(), DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
}
});
((MainActivity)getActivity()).setMService();
}
}

remove this line from fragment KeyListenerInit method because you already initialize object in Activity then why you again intialize this.
((MainActivity)getActivity()).setMService();
and remove this code from onCreate method because you already add this code in onStart method so no need in onCreate method:
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the session
} else {
if (mService == null) {
setMService();
}
}

Related

Override, SuppressLint onCreate(Bundle)' is already defined in 'My project'

In my MainActivity shows like that, I am pretty developer yet, How to replace or solve it, I tried many as know but unfortunately getting error "is already defined"
In my MainActivity shows like that, I am pretty developer yet, How to replace or solve it, I tried many as know but unfortunately getting error "is already defined"
How can I solve this code to going right?
BottomNavigationView bottomNavigation;
public Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loadLocale();
setContentView(R.layout.fragment_main);
//change actionbar title, if you dont change it will be according to your systems default language/english
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle(getResources().getString(R.string.app_name));
Button changeLang = findViewById(R.id.changeMyLang);
changeLang.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//show AlertDialog to display list of language, one can be selected
showChangeLanguageDialog();
}
});
}
private void showChangeLanguageDialog() {
//array of languages to display in alert dialog
final String[] listItems = {"English", "O'zbek"};
final AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
mBuilder.setTitle("Choose Language...");
mBuilder.setSingleChoiceItems(listItems, -1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (i == 0) {
//English
setLocale("en");
recreate();
} else if (i == 1) {
//O'zbek
setLocale("uz");
recreate();
}
//dismiss alert dialog when language selected
dialogInterface.dismiss();
}
});
AlertDialog mDialog =mBuilder.create();
//show alert dialog
mDialog.show();
}
DrawerLayout drawer;
ImageView imageView1;
BottomNavigationView.OnNavigationItemSelectedListener navigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
public boolean onNavigationItemSelected(MenuItem menuItem) {
String str = "";
switch (menuItem.getItemId()) {
case R.id.navigation_home:
toolbar.setTitle(getString(R.string.app_name));
MainActivity.this.openFragment(MainFragment.newInstance(str, str, MainActivity.this));
return true;
case R.id.navigation_map:
toolbar.setTitle("Workouts");
MainActivity.this.openFragment(Fragment_Workout.newInstance(str, str));
return true;
case R.id.navigation_walk:
toolbar.setTitle("Walk & Step");
MainActivity.this.openFragment(Fragment_Walk_and_Step.newInstance(str, str));
return true;
case R.id.navigation_news:
toolbar.setTitle("Reminders");
MainActivity.this.openFragment(Fragment_Reminder.newInstance(str, str));
return true;
default:
return false;
}
}
};
NavigationView navigationView;
Toolbar toolbar;
#SuppressLint("ResourceType")
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
if (VERSION.SDK_INT > 21) {
StrictMode.setThreadPolicy(new Builder().permitAll().build());
}
setContentView((int) R.layout.activity_main);
// StepDetectionServiceHelper.startAllIfEnabled(true, MainActivity.this);
this.navigationView = (NavigationView) findViewById(R.id.nav_views);
// bottomNavigation.setItemIconTintList(null);
this.imageView1 = (ImageView) findViewById(R.id.setting);
this.imageView1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// MainActivity.this.startActivity(new Intent(MainActivity.this, Setting_Activity.class));
}
});
if (VERSION.SDK_INT >= 21) {
Window window = getWindow();
window.addFlags(Integer.MIN_VALUE);
// window.setStatusBarColor(Color.parseColor("#EF5050"));
}
this.toolbar = initToolbar();
DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
this.drawer = drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle =
new ActionBarDrawerToggle(this, drawerLayout, this.toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
this.drawer.addDrawerListener(actionBarDrawerToggle);
this.drawer.addDrawerListener(new DrawerLayout.SimpleDrawerListener() {
public void onDrawerClosed(View view) {
}
public void onDrawerOpened(View view) {
}
});
actionBarDrawerToggle.syncState();
this.navigationView.setNavigationItemSelectedListener(this);
String str = "#ffffff";
// this.toolbar.setTitleTextColor(Color.parseColor(str));
// this.toolbar.getNavigationIcon().setColorFilter(Color.parseColor(str), Mode.MULTIPLY);
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.nav_view);
this.bottomNavigation = bottomNavigationView;
bottomNavigationView.setOnNavigationItemSelectedListener(this.navigationItemSelectedListener);
String str2 = "";
// MainActivity mainActivity = null;
openFragment(MainFragment.newInstance(str2, str2, this));
}
public void openFragment(Fragment fragment) {
FragmentTransaction beginTransaction = getSupportFragmentManager().beginTransaction();
beginTransaction.replace(R.id.nav_host_fragment, fragment);
beginTransaction.addToBackStack(null);
beginTransaction.commit();
}
public void loadFragmentworkout(Fragment fragment) {
FragmentTransaction beginTransaction = getSupportFragmentManager().beginTransaction();
beginTransaction.replace(R.id.nav_host_fragment, fragment);
beginTransaction.addToBackStack(null);
beginTransaction.commit();
toolbar.setTitle("workout");
bottomNavigation.setSelectedItemId(R.id.navigation_map);
}
public void loadFragment_water(Fragment fragment) {
FragmentTransaction beginTransaction = getSupportFragmentManager().beginTransaction();
beginTransaction.replace(R.id.nav_host_fragment, fragment);
beginTransaction.addToBackStack(null);
beginTransaction.commit();
toolbar.setTitle("Walk & Step");
bottomNavigation.setSelectedItemId(R.id.navigation_walk);
}
private Toolbar initToolbar() {
Toolbar toolbar2 = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar2);
return toolbar2;
}
public boolean onNavigationItemSelected(MenuItem menuItem) {
int itemId = menuItem.getItemId();
String str = "android.intent.extra.TEXT";
String str2 = "android.intent.extra.SUBJECT";
if (itemId == R.id.nav_rateus) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())));
} else if (itemId == R.id.nav_share) {
Intent intent2 = new Intent("android.intent.action.SEND");
intent2.setType("text/plain");
StringBuilder sb3 = new StringBuilder();
sb3.append("Best Free Sog'liq Bu Sport app download now.\n Thank You!\n https://play.google.com/store/apps/details?id=" + getPackageName());
sb3.append(getApplicationContext().getPackageName());
String sb4 = sb3.toString();
intent2.putExtra(str2, "Share App");
intent2.putExtra(str, sb4);
startActivity(Intent.createChooser(intent2, "Share via"));
} else if (itemId == R.id.nav_privacy) {
Uri uri = Uri.parse("https://the-life-bloga.blogspot.com/2020/01/blog-post.html");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
} else if (itemId == R.id.nav_telegram) {
Uri uri = Uri.parse("https://the-life-bloga.blogspot.com/2020/01/blog-post.html");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
} else if (itemId == R.id.nav_instagram) {
Uri uri = Uri.parse("https://www.instagram.com/sanatismoilov_official");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
} else if (itemId == R.id.nav_facebook) {
Uri uri = Uri.parse("https://www.facebook.com/Nodirovich98");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
} else if (itemId == R.id.nav_about) {
Uri uri = Uri.parse("https://msto.me/sanat_ismoilov");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
} else if (itemId == R.id.nav_covid) {
Uri uri = Uri.parse("https://coronavirus.uz/uz");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
this.drawer.closeDrawer((int) GravityCompat.START);
return true;
}
public void onBackPressed() {
StepDetectionServiceHelper.stopAllIfNotRequired(this.getApplicationContext());
// StepDetectionServiceHelper.startAllIfEnabled(true, MainActivity.this);
}
public void setLocale(String lang) {
Locale locale = new Locale(lang);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
//save data to shared preferences
SharedPreferences.Editor editor = getSharedPreferences("Setting", MODE_PRIVATE).edit();
editor.putString("My_Lang", lang);
editor.apply();
}
// load language saved in shared prefences
public void loadLocale() {
SharedPreferences prefs = getSharedPreferences("Setting", Activity.MODE_PRIVATE);
String language = prefs.getString("My_Lang", "");
setLocale(language);`
}
}```

Turn Activity with getHttpResponse to Fragment

I find it hard to use Fragment because I still don't have enough knowledge about it, so I tried to create my project using an Activity class first, but I still have to convert it into fragment cause I was using a left nav. I need someone's guide because I can't seem to find anything on the internet
Everything turns out to be fine but when I change this section of the code
new ReportsTab.GetHttpResponse(ReportsTab.this).execute();
It would display an error "Gethttpresponse cannot be applied"
This is my Activity Class
public class Reports extends AppCompatActivity {
ListView ReportsListView;
ProgressBar progressBar;
Button status;
String HttpUrl = "http://................../reports_app2.php";
List<String> IdList = new ArrayList<>();
AlertDialog alertDialog;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reports);
ReportsListView = (ListView)findViewById(R.id.listview1);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
new GetHttpResponse(Reports.this).execute();
//Adding ListView Item click Listener.
ReportsListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
Intent intent = new Intent(Reports.this,MainActivity.class);
// Sending ListView clicked value using intent.
intent.putExtra("ListViewValue", IdList.get(position).toString());
startActivity(intent);
//Finishing current activity after open next activity.
finish();
}
});
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
NavigationView nvDrawer = (NavigationView) findViewById(R.id.nv);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setupDrawerContent(nvDrawer);
}
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
String JSonResult;
List<ReportsJava> ReportsList;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
// Passing HTTP URL to HttpServicesClass Class.
HttpServicesClass httpServicesClass = new HttpServicesClass(HttpUrl);
try
{
httpServicesClass.ExecutePostRequest();
if(httpServicesClass.getResponseCode() == 200)
{
JSonResult = httpServicesClass.getResponse();
if(JSonResult != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(JSonResult);
JSONObject jsonObject;
ReportsJava reports;
ReportsList = new ArrayList<ReportsJava>();
for(int i=0; i<jsonArray.length(); i++)
{
reports = new ReportsJava();
jsonObject = jsonArray.getJSONObject(i);
// Adding Student Id TO IdList Array.
IdList.add(jsonObject.getString("id").toString());
//Adding Student Name.
if("0".equals(jsonObject.getString("status").toString()))
{
reports.LightpostStatus = "BLACKOUT";
}
else if("1".equals(jsonObject.getString("status").toString()))
{
reports.LightpostStatus = "FIXED";
}
else if("2".equals(jsonObject.getString("status").toString()))
{
reports.LightpostStatus = "DEFECTIVE";
}
reports.LightpostName = jsonObject.getString("lightpost_code").toString();
reports.LightpostAddress = jsonObject.getString("lightpost_location").toString();
reports.LightpostTime = jsonObject.getString("lightpost_time").toString();
ReportsList.add(reports);
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
else
{
Toast.makeText(context, httpServicesClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressBar.setVisibility(View.GONE);
ReportsListView.setVisibility(View.VISIBLE);
ReportsListAdapterClass adapter = new ReportsListAdapterClass(ReportsList, context);
ReportsListView.setAdapter(adapter);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menuLogout:
SharedPrefManager.getInstance(this).logout();
finish();
startActivity(new Intent(this, MainActivity.class));
break;
case R.id.menuSettings:
Toast.makeText(this, "You clicked settings", Toast.LENGTH_LONG).show();
break;
}
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
public void selectItemDrawer(MenuItem menuItem){
Fragment myFragment = null;
Class fragmentClass;
switch (menuItem.getItemId()){
case R.id.viewlights:
fragmentClass= ViewLightpost.class;
break;
case R.id.viewreports:
fragmentClass= ReportsTab.class;
break;
case R.id.viewaccount:
fragmentClass= EditAccount.class;
break;
case R.id.viewabout:
fragmentClass= AboutTab.class;
break;
default:
fragmentClass= ViewLightpost.class;
}
try{
myFragment=(Fragment) fragmentClass.newInstance();
}
catch (Exception e)
{
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flcontent,myFragment).commit();
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
mDrawerLayout.closeDrawers();
}
private void setupDrawerContent(NavigationView navigationView){
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
selectItemDrawer(item);
return false;
}
});
}
}
new ReportsTab.GetHttpResponse(ReportsTab.this.getActivity()).execute();
Get the activity from the fragment instance.

Show only numbers from text

I have a string that both the letter and the number.
As shown below:
I want to separate numbers from letters and When the user clicks the numbers
these numbers are displayed on the screen as buttons.
Such as following photos:
I have a activity that takes this string to another activity.
Basically what I should do? thanks.
My Activity1:
public class BoxActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.box);
TextView textView = (TextView) findViewById(R.id.txtView);
Bundle bundle = getIntent().getExtras();
if(bundle != null){
String strBox = bundle.getString("fln");
textView.setText(strBox);
}
}
My Activity2
public class SmsInbox extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, AdapterView.OnItemClickListener {
private static SmsInbox inst;
ArrayList<String> smsMessagesList = new ArrayList<String>();
ListView smsListView;
ArrayAdapter arrayAdapter;
public static SmsInbox instance() {
return inst;
}
#Override
public void onStart() {
super.onStart();
inst = this;
}
DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms_inbox);
smsListView = (ListView) findViewById(R.id.SmsList);
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, smsMessagesList);
smsListView.setAdapter(arrayAdapter);
smsListView.setOnItemClickListener(this);
if(ContextCompat.checkSelfPermission(getBaseContext(), "android.permission.READ_SMS") == PackageManager.PERMISSION_GRANTED) {
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(Uri.parse("content://sms/inbox"), null, null,
null, null);
int indexBody = cursor.getColumnIndex("body");
int indexAddr = cursor.getColumnIndex("address");
if (indexBody < 0 || !cursor.moveToFirst()) return;
arrayAdapter.clear();
do {
String str = "?????? ??: " + cursor.getString(indexAddr) +
"\n" + cursor.getString(indexBody) + "\n";
arrayAdapter.add(str);
} while (cursor.moveToNext());
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
toggle.setDrawerIndicatorEnabled(false);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
public void updateList(final String smsMessage) {
arrayAdapter.insert(smsMessage, 0);
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
try {
String[] smsMessages = smsMessagesList.get(pos).split("\n");
String address = smsMessages[0];
String smsMessage = "";
for (int i = 1; i < smsMessages.length; ++i) {
smsMessage += smsMessages[i];
}
/* String smsMessageStr = address + "\n";
smsMessageStr += smsMessage;
Toast.makeText(this, smsMessageStr, Toast.LENGTH_SHORT).show();
*/
Intent intent = new Intent(this, BoxActivity.class);
String strBox = smsMessage;
intent.putExtra("fln", strBox);
startActivity(intent);
/*Pattern isnumbers = Pattern.compile("[0-9]+$");
Matcher numberMatch = isnumbers.matcher(strBox);
if(numberMatch.matches()){
Toast.makeText(this, "" + numberMatch, Toast.LENGTH_LONG).show();
} */
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.END)) {
drawer.closeDrawer(GravityCompat.END);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#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.menuRight) {
if (drawer.isDrawerOpen(Gravity.RIGHT)) {
drawer.closeDrawer(Gravity.RIGHT);
} else {
drawer.openDrawer(Gravity.RIGHT);
}
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.Home_page) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
} else if (id == R.id.not_pay) {
if (SmsInbox.this.drawer != null && SmsInbox.this.drawer.isDrawerOpen(GravityCompat.END)) {
SmsInbox.this.drawer.closeDrawer(GravityCompat.END);
} else {
Intent intent = new Intent(this, MainActivity.class);
SmsInbox.this.startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
}
} else if (id == R.id.date_pay) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
} else if (id == R.id.bill_sms) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
} else if (id == R.id.help_menu) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
} else if (id == R.id.for_us) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
} else if (id == R.id.exit_app) {
finish();
overridePendingTransition(0, 0);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.END);
return true;
}
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
you should use Regex to exgtract Numbers from String
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher("There are more than -2 and less than 12 numbers here");
while (m.find()) {
System.out.println(m.group());
}
on view click listener you can do this.
#Override
void onClick(View view){
String allTxt = editText.getText.toString()
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher(allTxt);
while (m.find()) {
System.out.println(m.group());//here are the numbers then you can set it to another TextView
}
}
String str = "test-asdfdfg 455 yuoyr 4";
str = str.replaceAll("[^-?0-9]+", " ");
System.out.println(Arrays.asList(str.trim().split(" ")));
Output [455, 4] use this array to show chooser

Non-functioning of the application when adding Facebook Like Button

I am working on adding Facebook Like button to the application everything is normal but the problem when running the application and do not know what exactly is the problem
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
public static final String PROPERTY_REG_ID = "notifyId";
private static final String PROPERTY_APP_VERSION = "appVersion";
GoogleCloudMessaging gcm;
SharedPreferences preferences;
String reg_cgm_id;
static final String TAG = "MainActivity";
private AdView mAdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Settings.sdkInitialize(this);
LikeView likeView = (LikeView) findViewById(R.id.like_view);
likeView.setObjectId("https://m.facebook.com/DZ.4.EverR");
likeView.setLikeViewStyle(LikeView.Style.STANDARD);
likeView.setAuxiliaryViewPosition(LikeView.AuxiliaryViewPosition.INLINE);
likeView.setHorizontalAlignment(LikeView.HorizontalAlignment.CENTER);
preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
}
//show admob banner ad
mAdView = (AdView) findViewById(R.id.adView);
mAdView.loadAd(new AdRequest.Builder().build());
mAdView.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
}
#Override
public void onAdFailedToLoad(int error) {
mAdView.setVisibility(View.GONE);
}
#Override
public void onAdLeftApplication() {
}
#Override
public void onAdOpened() {
}
#Override
public void onAdLoaded() {
mAdView.setVisibility(View.VISIBLE);
}
});
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mNavigationView = (NavigationView) findViewById(R.id.main_drawer) ;
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.frame_container, new FragmentRecent()).commit();
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
//setTitle(menuItem.getTitle());
if (menuItem.getItemId() == R.id.drawer_recent) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, new FragmentRecent()).commit();
}
if (menuItem.getItemId() == R.id.drawer_category) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, new FragmentCategory()).commit();
}
if (menuItem.getItemId() == R.id.drawer_favorite) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, new FragmentFavorite()).commit();
}
if (menuItem.getItemId() == R.id.drawer_rate) {
final String appName = getPackageName();
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + appName)));
}
}
if (menuItem.getItemId() == R.id.drawer_more) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.play_more_apps))));
}
if (menuItem.getItemId() == R.id.drawer_setting) {
Intent i = new Intent(getBaseContext(), SettingsActivity.class);
startActivity(i);
}
return false;
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
// init analytics tracker
((Analytics) getApplication()).getTracker();
// GCM
if (checkPlayServices()) {
gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
String reg_cgm_id = getRegistrationId(getApplicationContext());
Log.i(TAG, "Play Services Ok.");
if (reg_cgm_id.isEmpty()) {
Log.i(TAG, "Find Register ID.");
registerInBackground();
}
} else {
Log.i(TAG, "No valid Google Play Services APK found.");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(menuItem);
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
else {
super.onBackPressed();
}
}
#Override
public void onStart() {
super.onStart();
// analytics
GoogleAnalytics.getInstance(this).reportActivityStart(this);
}
#Override
public void onStop() {
super.onStop();
// analytics
GoogleAnalytics.getInstance(this).reportActivityStop(this);
}
#Override
protected void onPause() {
mAdView.pause();
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
mAdView.resume();
}
#Override
protected void onDestroy() {
mAdView.destroy();
super.onDestroy();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
LikeView.handleOnActivityResult(this, requestCode, resultCode, data);
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(MainActivity.this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this, 9000).show();
} else {
Log.i(TAG, "This device is not supported.");
}
return false;
}
return true;
}
private void storeRegistrationId(Context context, String regId) {
int appVersion = getAppVersion(context);
Log.i(TAG, "Saving regId on app version " + appVersion);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
}
private String getRegistrationId(Context context) {
String registrationId = preferences.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
// Check if app was updated; if so, it must clear the registration ID
// since the existing regID is not guaranteed to work with the new
// app version.
int registeredVersion = preferences.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.i(TAG, "Analytics version changed.");
return "";
}
return registrationId;
}
private void registerInBackground() {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(MainActivity.this);
}
reg_cgm_id = gcm.register(getString(R.string.google_api_sender_id));
msg = "Device registered, registration ID=" + reg_cgm_id;
Log.d(TAG, "ID GCM: " + reg_cgm_id);
sendRegistrationIdToBackend();
storeRegistrationId(MainActivity.this, reg_cgm_id);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
#Override
protected void onPostExecute(String msg) {
}
}.execute(null, null, null);
}
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (PackageManager.NameNotFoundException e) {
throw new RuntimeException("Could not get package name: " + e);
}
}
private void sendRegistrationIdToBackend() {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("token", reg_cgm_id));
new HttpTask(null, MainActivity.this, Config.SERVER_URL + "/register.php", nameValuePairs, false).execute();
}
}
This is the important part of your log:
java.lang.NullPointerException: Attempt to invoke virtual method
'void com.facebook.widget.LikeView.setObjectId(java.lang.String)'
on a null object reference at android.app.ActivityThread.performLaunchActivity
It's saying that you're trying to call the method setObjectId on a LikeView that is null. So, step through that part of the code and figure out why the LikeView is null.

How implements Android in-app-billing

I have integrate Android In-App Billing in my principal activity (MainActivity). The test works !
But, the product to be purchased is the removal of the ads. The ad is implements in a fragment. So, I can't disable ad.
This is my code :
MainActivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = "com.mypackage.inappbilling";
public static final String ITEM_SKU = "test2";
NavigationView navigationView = null;
Toolbar toolbar = null;
IabHelper mHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//InAppBilling
String base64EncodedPublicKey = "#string/base64";
// compute your public key and store it in base64EncodedPublicKey
mHelper = new IabHelper(this, base64EncodedPublicKey);
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
#SuppressLint("LongLogTag")
public void onIabSetupFinished(IabResult result) {
if (!result.isSuccess()) {
// Oh no, there was a problem.
Log.d(TAG, "Problem setting up In-app Billing: " + result);
}
// Hooray, IAB is fully set up!
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data)
{
if (!mHelper.handleActivityResult(requestCode,
resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener
= new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result,
Purchase purchase)
{
if (result.isFailure()) {
// Handle error
return;
}
else if (purchase.getSku().equals(ITEM_SKU)) {
consumeItem();
}
}
};
public void consumeItem() {
mHelper.queryInventoryAsync(mReceivedInventoryListener);
}
IabHelper.QueryInventoryFinishedListener mReceivedInventoryListener
= new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result,
Inventory inventory) {
if (result.isFailure()) {
// Handle failure
} else {
mHelper.consumeAsync(inventory.getPurchase(ITEM_SKU),
mConsumeFinishedListener);
}
}
};
IabHelper.OnConsumeFinishedListener mConsumeFinishedListener =
new IabHelper.OnConsumeFinishedListener() {
public void onConsumeFinished(Purchase purchase,
IabResult result) {
}
};
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_agenda) {
//Set the fragment initially
MainFragment fragment = new MainFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
// Handle the camera action
} else if (id == R.id.nav_cadena) {
mHelper.launchPurchaseFlow(this, ITEM_SKU, 10001,
mPurchaseFinishedListener, "mypurchasetoken");
} else if (id == R.id.nav_apropos) {
//Set the fragment initially
AproposFragment fragment = new AproposFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
#Override
public void onDestroy() {
super.onDestroy();
if (mHelper != null) mHelper.dispose();
mHelper = null;
}
MainFragment.java
public class MainFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
SwipeRefreshLayout swipeLayout;
public static AdView adView;
private RecyclerView recyclerView;
private View rootView;
public MainFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_main, container, false);
StartProgress();
updateInterface();
if (Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
swipeLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorSchemeColors(getResources().getColor(R.color.colorPrimary),
getResources().getColor(R.color.colorPrimaryDark), getResources().getColor(R.color.colorAccent));
}
private void updateInterface() {
if (purchase.getSku().equals(MainActivity.ITEM_SKU)) {
displayAd(false);
} else {
displayAd(true);
}
}
public void displayAd(boolean state) {
if (state) {
if (adView == null) {
// Google has dropped Google Play Services support for Froyo
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.FROYO) {
adView = (AdView) rootView.findViewById(R.id.adViewCardItem);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
}
}
} else {
if (adView != null) {
adView.destroy();
adView = null;
}
}
}
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
swipeLayout.setRefreshing(false);
}
}, 2000);
}
public void StartProgress() {
new AsyncProgressBar().execute();
}
private class AsyncProgressBar extends AsyncTask<Void, Void, Void> {
protected ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(getActivity());
dialog.setMessage("...");
dialog.setCancelable(false);
dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
//duration of progressbar
SystemClock.sleep(1000);
return null;
}
#Override
protected void onPostExecute(Void useless) {
.....
}
}
}
I'm stuck on this part of code :
private void updateInterface() {
if (purchase.getSku().equals(MainActivity.ITEM_SKU)) {
displayAd(false);
} else {
displayAd(true);
}
}
How can I appeal to the variable " purchase" my MainActivity.java ? Or maybe this is not the right method ? Can you please enlighten me on this?
Thanks in advance !
As far as I understand you use TrivialDrive example, check how premium purchase is implemented (find usages mIsPremium).
// Do we have the premium upgrade
Purchase premiumPurchase = inventory.getPurchase(SKU_PREMIUM);
mIsPremium = (premiumPurchase != null && verifyDeveloperPayload(premiumPurchase));
Disable ads by this variable.
Finally, I chose an intermediate solution : I created two fragments , one with the pub , and without advertising.
When the user makes the purchase , it is then the ad-free fragment starts.
Here the change of my code :
MainActivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = "com.mypackage.inappbilling";
public static final String ITEM_SKU = "test2";
NavigationView navigationView = null;
Toolbar toolbar = null;
IabHelper mHelper;
boolean mIsPremium = false;
boolean mIsUserPremium = false;
boolean searchAllowed = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences prefs = getSharedPreferences(
"com.xxxxxx", 0);
mIsPremium = prefs.getBoolean("premium", false);
if (mIsPremium) {
MainFragmentDisAd fragment = new MainFragmentDisAd();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
} else {
MainFragment fragment = new MainFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
//InAppBilling
String base64EncodedPublicKey = "#string/base64";
// compute your public key and store it in base64EncodedPublicKey
mHelper = new IabHelper(this, base64EncodedPublicKey);
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
#SuppressLint("LongLogTag")
public void onIabSetupFinished(IabResult result) {
if (!result.isSuccess()) {
// Oh no, there was a problem.
Log.d(TAG, "Problem setting up In-app Billing: " + result);
}
// Hooray, IAB is fully set up. Now, let's get an inventory of
Log.d(TAG, "Setup successful. Querying inventory.");
mHelper.queryInventoryAsync(mGotInventoryListener);
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data)
{
if (!mHelper.handleActivityResult(requestCode,
resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener
= new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result,
Purchase purchase)
{
if (result.isFailure()) {
// Handle error
return;
}
if (!verifyDeveloperPayload(purchase)) {
complain("Erreur lors de l'achat. Authentification non reconnue.");
return;
}
Log.d(TAG, "Purchase successful.");
if (purchase.getSku().equals(ITEM_SKU)) {
// bought the premium upgrade!
Log.d(TAG, "It's ok.");
alert("You are premiul");
mIsPremium = true;
SharedPreferences prefs = getBaseContext().getSharedPreferences(
"com.xxxxx", 0);
prefs.edit().putBoolean("premium", true).apply();
}
};
public void consumeItem() {
mHelper.queryInventoryAsync(mReceivedInventoryListener);
}
IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
#SuppressLint("LongLogTag")
#Override
public void onQueryInventoryFinished(IabResult result,
Inventory inventory) {
Log.d(TAG, "Inventory is finish.");
if (result.isFailure()) {
complain("Echec" + result);
return;
}
/*if (inventory.hasPurchase(PREM_SKU)) {
mHelper.consumeAsync(inventory.getPurchase(PREM_SKU), null);
}*/
Log.d(TAG, "Inventory is ok.");
Purchase premiumPurchase = inventory.getPurchase(ITEM_SKU);
mIsPremium = (premiumPurchase != null && verifyDeveloperPayload(premiumPurchase));
Log.d(TAG, "User is " + (mIsPremium ? "PREMIUM" : "NOT PREMIUM"));
if (mIsPremium) {
searchAllowed = true;
mIsUserPremium = true;
Log.d(TAG, "you must be premium...");
SharedPreferences prefs = getBaseContext().getSharedPreferences(
"com.xxxx", 0);
prefs.edit().putBoolean("premium", true).apply();
}
Log.d(TAG, "Initial inventory query finished; enabling main UI.");
}
};
IabHelper.OnConsumeFinishedListener mConsumeFinishedListener =
new IabHelper.OnConsumeFinishedListener() {
public void onConsumeFinished(Purchase purchase,
IabResult result) {
}
};
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_agenda) {
if (mIsPremium) {
MainFragmentDisAd fragment = new MainFragmentDisAd();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
} else {
MainFragment fragment = new MainFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
}
} else if (id == R.id.nav_cadena) {
mHelper.launchPurchaseFlow(this, ITEM_SKU, 10001,
mPurchaseFinishedListener, "mypurchasetoken");
} else if (id == R.id.nav_apropos) {
//Set the fragment initially
AproposFragment fragment = new AproposFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
#Override
public void onDestroy() {
super.onDestroy();
if (mHelper != null) mHelper.dispose();
mHelper = null;
}
It's good for me, it works!

Categories

Resources