I am writing one app to display user's current address based on latitude and longitude but i am getting one error in this code on line Toast.makeText(this, "No address found try again", Toast.LENGTH_SHORT).show(); It's saying makeText in the type toast is not applicable for arguments. I am unbable to resolve this error.
Any help??
I am trying to display user address in a TextView, but i am not sure whether i am doing good or some runtime error may occur in future.
Here is my Main activity java code:
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationServices;
import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnItemSelectedListener, ConnectionCallbacks, OnConnectionFailedListener{
private static final int REQUEST_RESOLVE_ERROR = 1001;
private static final String DIALOG_ERROR = "dialog_error";
private static final String STATE_RESOLVING_ERROR = "resolving_error";
GoogleApiClient mGoogleApiClient;
protected Location mLastLocation;
private boolean mResolvingError=false;
private AddressResultReceiver mResultReceiver;
// Request code to use when launching the resolution activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner spinner = (Spinner) findViewById(R.id.shop_category);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.shop_category, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
mResolvingError = savedInstanceState != null
&& savedInstanceState.getBoolean(STATE_RESOLVING_ERROR, false);
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
TextView mytext = (TextView) view;
Toast.makeText(this,"You selected "+mytext.getText(),Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
protected void startIntentService() {
Intent intent = new Intent(this, FetchAddressIntentService.class);
intent.putExtra(Constants.RECEIVER, mResultReceiver);
intent.putExtra(Constants.LOCATION_DATA_EXTRA, mLastLocation);
startService(intent);
}
#Override
public void onConnected(Bundle arg0) {
boolean mAddressRequested=false;
// TODO Auto-generated method stub
TextView myLatitude = (TextView)findViewById(R.id.lat_value);
TextView myLongitude = (TextView)findViewById(R.id.lang_value);
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
myLatitude.setText(String.valueOf(mLastLocation.getLatitude()));
myLongitude.setText(String.valueOf(mLastLocation.getLongitude()));
if (!Geocoder.isPresent()) {
Toast.makeText(this, R.string.no_geocoder_available,
Toast.LENGTH_LONG).show();
return;
}
else{
mAddressRequested=true;
if (mAddressRequested) {
startIntentService();
}
}
}
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// TODO Auto-generated method stub
if (mResolvingError) {
Toast.makeText(this, "Resolving errors", Toast.LENGTH_SHORT).show();
return;
} else if (result.hasResolution()) {
try {
mResolvingError = true;
result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR);
} catch (SendIntentException e) {
// There was an error with the resolution intent. Try again.
mGoogleApiClient.connect();
}
} else {
// Show dialog using GoogleApiAvailability.getErrorDialog()
showErrorDialog(result.getErrorCode());
mResolvingError = true;
}
}
private void showErrorDialog(int errorCode) {
// Create a fragment for the error dialog
ErrorDialogFragment dialogFragment = new ErrorDialogFragment();
// Pass the error that should be displayed
Bundle args = new Bundle();
args.putInt(DIALOG_ERROR, errorCode);
dialogFragment.setArguments(args);
dialogFragment.show(getFragmentManager(), "errordialog");
}
public void onDialogDismissed() {
mResolvingError = false;
}
public static class ErrorDialogFragment extends DialogFragment {
public ErrorDialogFragment() { }
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Get the error code and retrieve the appropriate dialog
int errorCode = this.getArguments().getInt(DIALOG_ERROR);
return GoogleApiAvailability.getInstance().getErrorDialog(
this.getActivity(), errorCode, REQUEST_RESOLVE_ERROR);
}
#Override
public void onDismiss(DialogInterface dialog) {
((MainActivity) getActivity()).onDialogDismissed();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_RESOLVE_ERROR) {
mResolvingError = false;
if (resultCode == RESULT_OK) {
if (!mGoogleApiClient.isConnecting() &&
!mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
}
}
}
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(STATE_RESOLVING_ERROR, mResolvingError);
}
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
class AddressResultReceiver extends ResultReceiver {
public AddressResultReceiver(Handler handler) {
super(handler);
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
// Display the address string
// or an error message sent from the intent service.
String mAddressOutput = resultData.getString(Constants.RESULT_DATA_KEY);
// Show a toast message if an address was found.
if (resultCode == Constants.SUCCESS_RESULT) {
TextView myaddress=(TextView) findViewById(R.id.myaddress);
myaddress.setText(mAddressOutput);
}
else{
Toast.makeText(this, "No address found try again", Toast.LENGTH_SHORT).show();
}
}
}
}
Thank you in advance.
Replace this with MainActivity.this as the first parameter to your makeText() call. this is an instance of your AddressResultReceiver inner class. It is not your activity, and makeText() needs a Context, like an Activity.
Use getApplicationContext() instead of this. Use:
Toast.makeText(getApplicationContext(), "message", Toast.LENGTH_SHORT).show();
this refers to AddressResultReceiver which is not subclass of Context.
Toast.makeText() needs Context.
Related
I have been trying to do lock task mode or lock into my app without being able to access other apps with still being able to disable the feature. I have looked at tutorials and documentation but some methods were deprecated since they were made around 5 years ago (onActivityResult). I have tried to change to the new methods (registerForActivityResult) that I found, however when I launch my app and try to enable admin permission by tapping on the enable button, the admin permissions don't pop up, so I cannot check it. So, when I try to lock my phone from other apps nothing happens because I don't have admin permissions.My Code for MainActivity.class below:
package com.example.myapplication;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityOptions;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.example.myapplication.databinding.ActivityMainBinding;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.example.myapplication.helper.MqttHelper;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttMessage;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button lock, disable, enable;
private static final int RESULT_ENABLE = 11;
private DevicePolicyManager devicePolicyManager;
private ActivityManager activityManager;
private ComponentName componentName;
private AppBarConfiguration appBarConfiguration;
private ActivityMainBinding binding;
MqttHelper mqttHelper;
//ChartHelper mChart;
//LineChart chart;
TextView dataReceived;
private Button btnPublish;
// Allowlist two apps.
private static final String KIOSK_PACKAGE = "com.example.myapplication";
private static final String[] APP_PACKAGES = {KIOSK_PACKAGE};
// ...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
//setContentView(R.layout.activity_main);
devicePolicyManager = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE);
activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
componentName = new ComponentName(this, Controller.class);
lock = (Button) findViewById(R.id.lock);
enable = (Button) findViewById(R.id.enable);
disable = (Button) findViewById(R.id.disable);
lock.setOnClickListener(this);
enable.setOnClickListener(this);
disable.setOnClickListener(this);
dataReceived = (TextView) findViewById(R.id.textview_first);
startMqtt();
}
#Override
protected void onResume() {
super.onResume();
boolean isActive = devicePolicyManager.isAdminActive(componentName);
}
#Override
public void onClick(View view) {
if (view == lock) {
boolean active = devicePolicyManager.isAdminActive(componentName);
if(active) {
devicePolicyManager.lockNow();
} else {
Toast.makeText(this, "You need to enable the Admin Device Features", Toast.LENGTH_SHORT).show();
}
} else if (view == enable) {
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, componentName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,"You Should Enable the app!");
//someActivityResultLauncher.launch(intent);
// Caller
mGetContent.launch(intent);
// Receiver
//startActivityForResult(intent, RESULT_ENABLE);
} else if (view == disable) {
devicePolicyManager.removeActiveAdmin(componentName);
disable.setVisibility(View.GONE);
enable.setVisibility(View.VISIBLE);
}
}
ActivityResultLauncher<Intent> mGetContent = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
// Here, no request code
Intent data = result.getData();
Toast.makeText(MainActivity.this, "enabled", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode== Activity.RESULT_OK && requestCode == RESULT_ENABLE){
Toast.makeText(MainActivity.this, "enabled", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
super.onActivityResult(requestCode, resultCode, data);
}
/*#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
case RESULT_ENABLE:
if(resultCode== Activity.RESULT_OK ){
//btn_unblock.setText("Dissable");
//btn_block.setVisibility(View.VISIBLE);
Toast.makeText(MainActivity.this, "enabled", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, appBarConfiguration)
|| super.onSupportNavigateUp();
}
// MQTT Code
private void startMqtt(){
mqttHelper = new MqttHelper(getApplicationContext());
mqttHelper.mqttAndroidClient.setCallback(new MqttCallbackExtended() {
#Override
public void connectComplete(boolean b, String s) {
Log.w("Debug","Connected");
}
#Override
public void connectionLost(Throwable throwable) {
}
#Override
public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
Log.w("Debug",mqttMessage.toString());
dataReceived.setText(mqttMessage.toString());
//mChart.addEntry(Float.valueOf(mqttMessage.toString()));
}
#Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
});
}
}
I am trying to create an application which activates and deactivates Bluetooth, finds the paired Bluetooth devices and scans for discovered Bluetooth devices. I added the permissions to the AndroidManifest.xml. And everything seems to be ok. However when I debug the app on the device(Samsung Galaxy tab 3 Lite) I get NullPointerException and the application crashes. Do you have an idea what might cause the problem? Please find below my code and the exception stack trace.
package dyankov.mylibraryrecommender.MainActivities.GUI;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import dyankov.mylibraryrecommender.R;
import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import java.util.Set;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class AroundMeActivity extends Activity {
private static final int REQUEST_ENABLE_BT = 1;
private Button turnOn;
private Button offBtn;
private Button listBtn;
private Button findBtn;
private TextView text;
private BluetoothAdapter myBluetoothAdapter;
private Set<BluetoothDevice> pairedDevices;
private ListView myListView;
private ArrayAdapter<String> BTArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// take an instance of BluetoothAdapter - Bluetooth radio
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(myBluetoothAdapter == null) {
turnOn.setEnabled(false);
offBtn.setEnabled(false);
listBtn.setEnabled(false);
findBtn.setEnabled(false);
text.setText("Status: not supported");
Toast.makeText(getApplicationContext(),"Your device does not support Bluetooth",
Toast.LENGTH_LONG).show();
} else {
text = (TextView) findViewById(R.id.text);
turnOn = (Button)findViewById(R.id.turnOn);
turnOn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
on(v);
}
});
offBtn = (Button)findViewById(R.id.turnOff);
offBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
off(v);
}
});
listBtn = (Button)findViewById(R.id.paired);
listBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
list(v);
}
});
findBtn = (Button)findViewById(R.id.search);
findBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
find(v);
}
});
myListView = (ListView)findViewById(R.id.listView1);
// create the arrayAdapter that contains the BTDevices, and set it to the ListView
BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
myListView.setAdapter(BTArrayAdapter);
}
}
public void on(View view){
if (!myBluetoothAdapter.isEnabled()) {
Intent turnOnIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT);
Toast.makeText(getApplicationContext(),"Bluetooth turned on" ,
Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(),"Bluetooth is already on",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == REQUEST_ENABLE_BT){
if(myBluetoothAdapter.isEnabled()) {
text.setText("Status: Enabled");
} else {
text.setText("Status: Disabled");
}
}
}
public void list(View view){
// get paired devices
pairedDevices = myBluetoothAdapter.getBondedDevices();
// put it's one to the adapter
for(BluetoothDevice device : pairedDevices)
BTArrayAdapter.add(device.getName()+ "\n" + device.getAddress());
Toast.makeText(getApplicationContext(),"Show Paired Devices",
Toast.LENGTH_SHORT).show();
}
final BroadcastReceiver bReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// add the name and the MAC address of the object to the arrayAdapter
BTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
BTArrayAdapter.notifyDataSetChanged();
}
}
};
public void find(View view) {
if (myBluetoothAdapter.isDiscovering()) {
// the button is pressed when it discovers, so cancel the discovery
myBluetoothAdapter.cancelDiscovery();
}
else {
BTArrayAdapter.clear();
myBluetoothAdapter.startDiscovery();
registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
}
public void off(View view){
myBluetoothAdapter.disable();
text.setText("Status: Disconnected");
Toast.makeText(getApplicationContext(),"Bluetooth turned off",
Toast.LENGTH_LONG).show();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(bReceiver);
}
}
And here is my Logcat file:
Caused by: java.lang.NullPointerException
at dyankov.mylibraryrecommender.MainActivities.GUI.AroundMeActivity.onCreate(AroundMeActivity.java:60)
at android.app.Activity.performCreate(Activity.java:5326)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2225)
The code on line 60 is:
turnOn.setOnClickListener(new OnClickListener() { ... }
put turnOn = (Button)findViewById(R.id.turnOn) and all your Button object initialization before turnOn.setEnabled(false);
You try to use button before you set value for it.
Try this code:
text = (TextView) findViewById(R.id.text);
turnOn = (Button)findViewById(R.id.turnOn);
if(myBluetoothAdapter == null) {
turnOn.setEnabled(false);
offBtn.setEnabled(false);
listBtn.setEnabled(false);
findBtn.setEnabled(false);
text.setText("Status: not supported");
Toast.makeText(getApplicationContext(),"Your device does not support Bluetooth",
Toast.LENGTH_LONG).show();
} else {
turnOn.setOnClickListener(new OnClickListener() {
This is my first time working with fragments. I'm implementing a facebook login. When I add the piece of code for the fragment
/* FACEBOOK FRAGMENT SETUP */
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragment = new MainFragment();
getSupportFragmentManager()
.beginTransaction()
.add(android.R.id.content, mainFragment)
.commit();
} else {
// Or set the fragment from restored state info
mainFragment = (MainFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
then none of the onClickListeners for my buttons or text views work. I'm not sure why this is happening. Can anyone shed light on this?
Main Activity Code
public class ActivityLogin extends FragmentActivity {
// label to display gcm messages
TextView lblMessage;
// Asyntask
AsyncTask<Void, Void, Void> mRegisterTask;
private EditText edt_username, edt_password;
public String gcm_id, un, pw, tab;
public ProgressDialog pdialog;
static int count = 0;
public String gcm_regid;
ConnectionDetector cd;
AlertDialogManager alert = new AlertDialogManager();
SharedPreferences sp1;
GPSTracker gpstracker;
RequestQueue queue;
//FB FRAGMENT
private MainFragment mainFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent in = getIntent();
tab = in.getStringExtra("tab");
queue = Volley.newRequestQueue(this);
//Check for saved credentials.
sp1=getSharedPreferences("Login",MODE_PRIVATE);
un = sp1.getString("un", "");
pw = sp1.getString("pw", "");
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(this);
gpstracker = new GPSTracker(getApplicationContext());
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
//GCMRegistrar.checkManifest(this);
cd = new ConnectionDetector(getApplicationContext());
//registerReceiver(mHandleMessageReceiver, new IntentFilter(DISPLAY_MESSAGE_ACTION));
final String regId = GCMRegistrar.getRegistrationId(this);
// Check if regid already presents
if (regId.equals("")) {
// Registration is not present, register now with GCM
GCMRegistrar.register(this, SENDER_ID);
gcm_id=GCMRegistrar.getRegistrationId(this);
} else {
gcm_id=regId;
// Device is already registered on GCM
if (GCMRegistrar.isRegisteredOnServer(this)) {
// Skips registration.
Toast.makeText(getApplicationContext(), "Already registered with GCM", Toast.LENGTH_LONG).show();
}
}
/*if(un==""){*/
setContentView(R.layout.login_layout);
Button login = (Button) findViewById(R.id.btn_login);
/* init EditText */
edt_username = (EditText) findViewById(R.id.edt_userNameLogin);
edt_password = (EditText) findViewById(R.id.edt_PasswordLogin);
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (edt_username.getText().toString().equalsIgnoreCase("")) {
alert.showAlertDialog(ActivityLogin.this, "KpFun alert!",
"Username no empty!", false);
edt_username.requestFocus();
return;
}
if (edt_password.getText().toString().equalsIgnoreCase("")) {
alert.showAlertDialog(ActivityLogin.this, "KpFun alert!",
"Password no empty!", false);
edt_password.requestFocus();
return;
}
if (!cd.isConnectingToInternet()) {
alert.showAlertDialog(ActivityLogin.this, "KpFun alert!",
"No network, Please check your data connection!",
false);
return;
}
Login();
}
});
TextView backLink = (TextView) findViewById(R.id.tv_Back);
backLink.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent inRegister = new Intent(ActivityLogin.this,
SplashScreen.class);
startActivity(inRegister);
finish();
}
});
/*}else{
Login();
}*/
/* FACEBOOK FRAGMENT SETUP */
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragment = new MainFragment();
getSupportFragmentManager()
.beginTransaction()
.add(android.R.id.content, mainFragment)
.commit();
} else {
// Or set the fragment from restored state info
mainFragment = (MainFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
if(!un.equals("")){
Login();
}
}
/* MORE STUFF TAKEN OUT */
FRAGMENT CODE
package com.kpfunusa1;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.facebook.Response;
import com.facebook.Request;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
public class MainFragment extends Fragment {
private static final String TAG = "MainFragment";
private UiLifecycleHelper uiHelper;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.login_layout, container, false);
LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
authButton.setFragment(this);
authButton.setReadPermissions(Arrays.asList("public_profile", "email", "user_friends", "user_birthday", "user_location", "user_website", "user_likes", "user_status"));
return view;
}
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
private void onSessionStateChange(Session session, SessionState state, Exception exception)
{
if (state.isOpened())
{
Log.i("facebook", "Logged in...");
Request.newMeRequest(session, new Request.GraphUserCallback()
{
#Override
public void onCompleted(GraphUser user, Response response)
{
if(user!=null)
{
String test=user.getName();
test =user.getProperty("email")+"";
test=(user.getProperty("gender")+"");
test=(user.getId()+"");
test=user.getBirthday();
test=user.getUsername();
test=user.getId();
}
else
{
String test=("its null");
test=(response.getError().getErrorMessage());
}
}
}).executeAsync();
}
else if (state.isClosed())
{
Log.i("facebook", "Logged out...");
}
}
#Override
public void onResume() {
super.onResume();
// For scenarios where the main activity is launched and user
// session is not null, the session state change notification
// may not be triggered. Trigger it if it's open/closed.
Session session = Session.getActiveSession();
if (session != null &&
(session.isOpened() || session.isClosed()) ) {
onSessionStateChange(session, session.getState(), null);
}
uiHelper.onResume();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
}
UiLifecycleHelper should be created and called all on*(Create/Resume etc) methods in Login activity, because onActivityResult in Fragment never be called.
And you should implement UI(login btn etc) only in fragment code. In Activity.setContentView you should set layout where defined login fragment.
Have you tried import the correct library in your Main Activity?
try import:
import android.support.v4.app.FragmentActivity;
In my Android app, I am trying to place a ListView in my FragmentActivity. Unfortunately there is no such thing as FragmentListActivity. The problem is that I can't call setListAdapter() and onListItemClick() methods.
So I did a lot of research and I went to my XML file and manually added the ListView there. Then instead of getListView(), I declared a ListView variable so I could call the methods on my new ListView variable. Unfortunately the method is still riddled with errors The method is unable to be resolved etc.
Here is my java code:
package com.spicycurryman.getdisciplined10.app;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import com.javatechig.listapps.ApplicationAdapter;
import java.util.ArrayList;
import java.util.List;
public class InstalledAppActivity extends FragmentActivity {
private PackageManager packageManager = null;
private List<ApplicationInfo> applist = null;
private ApplicationAdapter listadaptor = null;
//Implementing the Listview Programatically
ListView InstalledAppList = (ListView) findViewById(R.id.Installed_List);
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
packageManager = getPackageManager();
new LoadApplications().execute();
return inflater.inflate(R.layout.installed_apps, container, false);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.block, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
boolean result = true;
switch (item.getItemId()) {
case R.id.main_text: {
displayAboutDialog();
break;
}
default: {
result = super.onOptionsItemSelected(item);
break;
}
}
return result;
}
private void displayAboutDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.app_name));
builder.setMessage(getString(R.string.slogan));
builder.setPositiveButton("Know More", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://javatechig.com"));
startActivity(browserIntent);
dialog.cancel();
}
});
builder.setNegativeButton("No Thanks!", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.show();
}
//here
InstalledAppList.setOnItemClickListener(new OnItemClickListener()){
#Override
public void onItemClick(AdapterView <?> arg0, View view, int index, long id){
ApplicationInfo app = applist.get(index);
try {
Intent intent = packageManager
.getLaunchIntentForPackage(app.packageName);
if (null != intent) {
startActivity(intent);
}
} catch (ActivityNotFoundException e) {
Toast.makeText(InstalledAppActivity.this, e.getMessage(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(InstalledAppActivity.this, e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
});
private List<ApplicationInfo> checkForLaunchIntent(List<ApplicationInfo> list) {
ArrayList<ApplicationInfo> applist = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info : list) {
try {
if (null != packageManager.getLaunchIntentForPackage(info.packageName)) {
applist.add(info);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return applist;
}
private class LoadApplications extends AsyncTask<Void, Void, Void> {
private ProgressDialog progress = null;
#Override
protected Void doInBackground(Void... params) {
applist = checkForLaunchIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA));
listadaptor = new ApplicationAdapter(InstalledAppActivity.this,
R.layout.snippet_list_row, applist);
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPostExecute(Void result) {
//setListAdapter(listadaptor);
InstalledAppList.setAdapter(listadaptor);
progress.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(InstalledAppActivity.this, null,
"Loading application info...");
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
}
Here is my XML File:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/Installed_List"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Try this..
You have missed onCreate
ListView InstalledAppList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.installed_apps);
InstalledAppList = (ListView) findViewById(R.id.Installed_List);
packageManager = getPackageManager();
new LoadApplications().execute();
InstalledAppList.setOnItemClickListener(new OnItemClickListener()){
#Override
public void onItemClick(AdapterView <?> arg0, View view, int index, long id){
ApplicationInfo app = applist.get(index);
try {
Intent intent = packageManager
.getLaunchIntentForPackage(app.packageName);
if (null != intent) {
startActivity(intent);
}
} catch (ActivityNotFoundException e) {
Toast.makeText(InstalledAppActivity.this, e.getMessage(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(InstalledAppActivity.this, e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
});
}
and remove onCreateView and add ItemClickListener also inside onCreate
public class MyAndroidVersionListFragment extends ListFragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
CustomDoctorsListAdapter adapter= new CustomDoctorsListAdapter(getActivity(), getResources().getStringArray(R.array.doctors_name), getResources().getStringArray(R.array.doctors_address),
getResources().getStringArray(R.array.doctors_category), getResources().obtainTypedArray(R.array.doctors_rating), getResources().getIntArray(R.array.doctors_clinic_distance));
getResources().obtainTypedArray(R.array.doctors_rating).recycle();
android.R.layout.simple_list_item_multiple_choice, android_versions);
setListAdapter(adapter);
Toast.makeText(getActivity(), "Mypostion"+position+"", Toast.LENGTH_LONG).show();
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
position = getArguments().getInt("second");
}
#Override
public void onStart() {
super.onStart();
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
try List fragment like this hope it will help you
This question already has answers here:
Cannot make a static reference to the non-static method
(8 answers)
Closed 8 years ago.
I am trying to call a method after clicking on a Button but I'm getting this error:
"Cannot make a static reference to a non-static method”
here is the code, the only problematic thing in the code is when I try to call reakcja(); in button Intencja. Can you please help me?
package com.example.buttonwork;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends ActionBarActivity {
public void reakcja(){
Intent i = new Intent(this, Intencja.class);
startActivity(i);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("click", "On create!");
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
Log.i("click","Teraz chyba pierwszy zapis instancji");
}
}
#Override
public void onStop(){
Log.i("click","onStop");
super.onStop();
}
#Override
public void onPause(){
Log.i("click","onPause");
super.onPause();
}
#Override
public void onResume(){
Log.i("click","onResume");
super.onResume();
}
#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);
Log.i("click","Pierwsze tworzenie 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();
if (id == R.id.action_settings) {
//Toast.makeText(item.getContext(), "elo", Toast.LENGTH_SHORT).show();
Log.i("click", "menu");
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
Button but1;
Button Intencja;
TextView tv1;
EditText et1;
Button raf,kas;
ToggleButton off;
SeekBar sk1;
int kto;
CheckBox cb1,cb2;
RatingBar rb1;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Log.i("click","Tutaj wszystko sie dzieje");
rb1 = (RatingBar) (rootView.findViewById(R.id.rb1));
/*rb1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(v.getContext(), String.valueOf(rb1.getProgress()), Toast.LENGTH_SHORT).show();
}
});*/
rb1.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
#Override
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
// TODO Auto-generated method stub
Toast.makeText(ratingBar.getContext(), String.valueOf(rating), Toast.LENGTH_SHORT).show();
}
});
Intencja = (Button) (rootView.findViewById(R.id.Intencja));
Intencja.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
reakcja();
}
});
cb1 = (CheckBox) (rootView.findViewById(R.id.cb1));
cb2 = (CheckBox) (rootView.findViewById(R.id.cb2));
off = (ToggleButton) (rootView.findViewById(R.id.toggleButton1));
off.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), off.getText(), Toast.LENGTH_SHORT).show();
}
});
sk1 = (SeekBar) (rootView.findViewById(R.id.seekBar1));
sk1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
//Toast.makeText(seekBar.getContext(), String.valueOf(progress), Toast.LENGTH_SHORT).show();
tv1.setText(String.valueOf(progress));
return;
}
});
/*sk1.setOnSeekBarChangeListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(v.getContext(), sk1.getProgress(), Toast.LENGTH_SHORT).show();
}
});*/
tv1 = (TextView) (rootView.findViewById(R.id.tv1));
et1 = (EditText) (rootView.findViewById(R.id.et1));
raf = (Button) (rootView.findViewById(R.id.button1));
raf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(v.getContext(), "Ralfo jest miszczem", Toast.LENGTH_SHORT).show();
kto = 1;
sk1.setProgress(50);
}
});
kas = (Button) (rootView.findViewById(R.id.button2));
kas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(v.getContext(), "Nie, to Ralfo jest miszczem", Toast.LENGTH_SHORT).show();
kto =2;
sk1.setProgress(50);
}
});
but1 = (Button) (rootView.findViewById(R.id.b1));
but1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
tv1.setText(et1.getText().toString());
Toast.makeText(v.getContext(), String.valueOf(cb1.isChecked() && cb2.isChecked()), Toast.LENGTH_SHORT).show();
// wyświetla Toasta true albo false sprawdzając CheckBoxy i robiąc na nich koniunkcję
}
});
return rootView;
}
}
}
PlaceholderFragment is a static class, so you cannot call non-static method reakcja() from it. Make reakcja() static or PlaceholderFragment non-static.