OkHttpClient throws an error when trying to load data from sharedPrefrences - java

I'm making an app that controls esp modules and I'm using OkHttpClient to make post web requests.
You can set the ip of the esp module in the settings tab(e.g. if your esp ip is 123.456.789, the url for web request would be http://123.456.789), I'm saving, loading and getting that data from my settings activity to my main activity using sharedPrefrences, but when I open the app, it just crashes with the error url == null.
The only way I got it to work would be if I load it something like this:
public String ip = SettingsActivity.ipEsp;
but then every time I re-open the app, I have to open the setting activity for the data to be loaded.(tried saving this value with sharedPrefrences, but it doesn't seem to work, it doesn't crash or anything it just doesn't work)
I would want to have it saved in a way so whenever I re-open the app, it remembers the ip address that i set in the settings.
Here's the main activity code:
public class MainActivity extends AppCompatActivity {
Button settings;
Button send;
TextView view;
TextView see;
public String urlS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
settings = (Button) findViewById(R.id.button);
send = (Button) findViewById(R.id.button2);
view = (TextView) findViewById(R.id.textView);
see = (TextView) findViewById(R.id.see);
SharedPreferences urls = getSharedPreferences("sPrefs", MODE_PRIVATE);
urlS = urls.getString("url", "http://0.0.0.0:8888");
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
client.newCall(requestlL).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()){
String myR = response.body().string();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
see.setText(myR);
}
});
}
}
});
view.setText(urlS);
}
}
);
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setting();
}
});
}
OkHttpClient client = new OkHttpClient();
String urllL = urlS;
Request requestlL = new Request.Builder()
.url(urllL)
.build();
public void setting() {
Intent intent = new Intent(this, MainActivity2.class);
startActivity(intent);
}
}
and this is the setting activity code:
public class MainActivity2 extends AppCompatActivity {
private Handler sHand = new Handler();
public static final String S_PREFS = "sPrefs";
public static final String URL = "url";
Button back;
Button save;
EditText url;
public String urlS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
back = (Button) findViewById(R.id.button3);
save = (Button) findViewById(R.id.button4);
url = (EditText) findViewById(R.id.edit);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
back();
}
});
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
urlS = url.getText().toString();
save();
}
});
load();
view();
}
public void back()
{
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
public void saveDataRunS()
{
sHand.post(saveDs);
}
private Runnable saveDs= new Runnable() {
#Override
public void run() {
save();
load();
sHand.postDelayed(this, 1);
}
};
public void save()
{
SharedPreferences sharedPreferences = getSharedPreferences("sPrefs", MODE_PRIVATE);
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putString(URL, url.getText().toString());
edit.apply();
}
public void load()
{
SharedPreferences sharedPreferences = getSharedPreferences(S_PREFS, MODE_PRIVATE);
urlS = sharedPreferences.getString(URL, "http://0.0.0.0:8888");
}
public void view()
{
url.setText(urlS);
}
}
and this is the error i get:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.test, PID: 18146
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.test/com.example.test.MainActivity}: java.lang.NullPointerException: url == null
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3222)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3437)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2041)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7386)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:980)
Caused by: java.lang.NullPointerException: url == null
at okhttp3.Request$Builder.url(Request.java:132)
at com.example.test.MainActivity.<init>(MainActivity.java:99)
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:95)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:45)
at android.app.Instrumentation.newActivity(Instrumentation.java:1250)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3210)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3437) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2041) 
at android.os.Handler.dispatchMessage(Handler.java:107) 
at android.os.Looper.loop(Looper.java:214) 
at android.app.ActivityThread.main(ActivityThread.java:7386) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:980) 

#leeo6002
In MainActivity2, save() method is called in the following fashion.
onCreate -> saveDataRunS ->sHand.post(saveDs) -> save -> edit.putString(URL, url.getText().toString());
Basically, you are fetching the value from the url editText as soon as activity's onCreate is triggered. Which means you are not waiting for the user to enter the value in the EditText. At least, this is one of the issue.
Honestly, You need to clean up your code, It is a lot of mess right now.

Related

XSharedPreferences always get default value in my xposed module

I tried many different ways but still not working.
Always get default values.
public class HookTest implements IXposedHookLoadPackage {
private XSharedPreferences sharedPreferences;
private final static String modulePackageName = HookTest.class.getPackage().getName();
public void handleLoadPackage(final XC_LoadPackage.LoadPackageParam lpparam) throws Throwable {
this.sharedPreferences = new XSharedPreferences(modulePackageName, "Values");
sharedPreferences.makeWorldReadable();
sharedPreferences.reload();
XposedBridge.log("Xposed_test value: " +sharedPreferences.getBoolean("isRunning", false));
}
}
i tried in MainActivity it's work fine
it's returen correct value
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button)findViewById(R.id.button);
editText=(EditText)findViewById(R.id.editText);
final SharedPreferences pref = this.getSharedPreferences("Values", Context.MODE_PRIVATE);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editText.setText(""+pref.getBoolean("isRunning", false));
if(pref.getBoolean("isRunning", false)==true) {
setVlaue(MainActivity.this, false);
}else {
setVlaue(MainActivity.this, true);
}
}
});
}
public void setVlaue(Context context,boolean isRunning) {
Intent intent = new Intent("my.action.MyReceiver");
intent.putExtra("isRunning", isRunning);
context.sendBroadcast(intent);
}
Setting right permissions to files (chmod +r shared_prefs shared_prefs/your_prefrences.xml) helps in most cases. But it isn't good trick.
Good solution is RemotePreferences that uses ContentProvider to access your prefs

Try to invoke virtual method on a null object reference [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to make a barcode scanner app, and I want to add scan results to a certain list. In the MainActivity, I have a certain button that should send me to MyList activity, but then the app crashes and I don't know how to solve it.
So here is my code:
public class MainActivity extends AbsRuntimePermission implements ZXingScannerView.ResultHandler{
private ZXingScannerView zXingScannerView;
private static final int REQUEST_PERMISSION = 10;
boolean ok = false, chk = false;
private String scanResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chk = getIntent().getBooleanExtra("check", chk);
if(chk) {
chk = false;
ok = true;
zXingScannerView = new ZXingScannerView(getApplicationContext());
setContentView(zXingScannerView);
zXingScannerView.setResultHandler(this);
zXingScannerView.startCamera();
}
}
public void scan(View view){
requestAppPermissions(new String[]{Manifest.permission.CAMERA}, R.string.msg, REQUEST_PERMISSION);
ok = true;
zXingScannerView = new ZXingScannerView(getApplicationContext());
setContentView(zXingScannerView);
zXingScannerView.setResultHandler(this);
zXingScannerView.startCamera();
}
#Override
public void onPermissionGranted(int requestCode) {
if(ok)
Toast.makeText(getApplicationContext(), "Permission Granted", Toast.LENGTH_LONG).show();
}
#Override
public void onResume(){
super.onResume();
if(ok)
{
if(zXingScannerView == null)
{
zXingScannerView = new ZXingScannerView(this);
setContentView(zXingScannerView);
}
zXingScannerView.setResultHandler(this);
zXingScannerView.startCamera();
}
}
#Override
protected void onPause() {
super.onPause();
zXingScannerView.stopCamera();
}
#Override
public void handleResult(final Result result) {
scanResult = result.getText();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Result");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
zXingScannerView.resumeCameraPreview(MainActivity.this);
}
});
builder.setNeutralButton("GO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(scanResult));
startActivity(intent);
}catch (Exception ex)
{
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, scanResult);
startActivity(intent);
}
}
});
builder.setNegativeButton("Add to list", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(MainActivity.this, MyList.class);
intent.putExtra("CODE", scanResult);
startActivity(intent);
}
});
builder.setMessage(scanResult);
AlertDialog alert = builder.create();
alert.show();
}
public void Lista(View view){
Intent iNtent = new Intent(MainActivity.this, MyList.class);
startActivity(iNtent);
}
}`
And this is my error report:
01-12 09:42:26.013 2670-2670/com.example.tchibo.justqr E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.tchibo.justqr, PID: 2670
java.lang.RuntimeException: Unable to pause activity {com.example.tchibo.justqr/com.example.tchibo.justqr.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void me.dm7.barcodescanner.zxing.ZXingScannerView.stopCamera()' on a null object reference at android.app.ActivityThread.performPauseActivityIfNeeded(ActivityThread.java:3976)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3942)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3916)
at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:3890)
at android.app.ActivityThread.-wrap15(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1605)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void me.dm7.barcodescanner.zxing.ZXingScannerView.stopCamera()' on a null object reference
Actually, it says that is trying to invoke virtual method void me.dm7.barcodescanner.zxing.ZXingScannerView.stopCamera() on a null object reference.
(sorry for the post style but i'm not familiar with it)
Well you create method scan(View view) in this method you initialize your camera(ZXingScannerView ) object but din't call anywhere. have look for solution
in onCreate():
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chk = getIntent().getBooleanExtra("check", chk);
zXingScannerView = new ZXingScannerView(getApplicationContext());
if(chk) {
chk = false;
ok = true;
zXingScannerView = new ZXingScannerView(getApplicationContext());
setContentView(zXingScannerView);
zXingScannerView.setResultHandler(this);
zXingScannerView.startCamera();
}
}
in onPause()
#Override
protected void onPause() {
super.onPause();
if(zXingScannerView!=null)
zXingScannerView.stopCamera();
}
You can check zXingScannerView before using it.
if (zXingScannerView != null){
zXingScannerView.stopCamera();
}
java.lang.RuntimeException: Unable to pause activity
{com.example.tchibo.justqr/com.example.tchibo.justqr.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
me.dm7.barcodescanner.zxing.ZXingScannerView.stopCamera()' on a null
object reference
the logcat is telling you the problem, which is this line :
zXingScannerView.stopCamera();
your app is trying to stop something that does not exist !!
trivial solution :
if(zXingScannerView!=null){
zXingScannerView.stopCamera();
}

Simple Chat Application with WebSocketClient

I am trying to learn how to make a connection via a websocket in android. I am trying to use the websocket client to send a message to server and then try to view it on the screen.
I can start the application, but when I type a message and then click the send Button I receive the following error:
org.java_websocket.exceptions.WebsocketNotConnectedException
Here is my MainActivity Class:
public class MainActivity extends AppCompatActivity {
private TextView userView;
private ListView listView;
private EditText textToSend;
private Button sendButton;
private WebClient webClient;
private JSONObject jsonObject;
private URI uri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userView = (TextView) findViewById(R.id.userView);
listView = (ListView) findViewById(R.id.listView);
textToSend = (EditText) findViewById(R.id.textToSend);
sendButton = (Button) findViewById(R.id.sendButton);
try {
uri = new URI("http://127.0.0.1:8080/chat");
} catch (URISyntaxException e) {
e.printStackTrace();
}
webClient = new WebClient(uri);
webClient.connect();
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
jsonObject = new JSONObject();
try {
jsonObject.put("message",textToSend.toString());
} catch (JSONException e) {
e.printStackTrace();
}
webClient.send(jsonObject.toString());
}
});
}
}
And here is the WebClient Class:
public class WebClient extends WebSocketClient {
public WebClient(URI serverURI) {
super(serverURI);
}
#Override
public void onOpen(ServerHandshake handshakedata) {
Log.e("Websocket", "Opened");
}
#Override
public void onMessage(String message) {
}
#Override
public void onClose(int code, String reason, boolean remote) {
}
#Override
public void onError(Exception ex) {
}
}
And this is logcat after clicking the send button:
--------- beginning of crash
10-30 20:09:50.830 2682-2682/example.com.chatapp E/AndroidRuntime: FATAL EXCEPTION: main Process: example.com.chatapp, PID: 2682
org.java_websocket.exceptions.WebsocketNotConnectedException
at org.java_websocket.WebSocketImpl.send(WebSocketImpl.java:566)
at org.java_websocket.WebSocketImpl.send(WebSocketImpl.java:543)
at org.java_websocket.client.WebSocketClient.send(WebSocketClient.java:171)
at ziad.example.com.chatapp.MainActivity$1.onClick(MainActivity.java:60)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Sinch call button error?

I am trying to access a class in another class and i can getting this error. I am using sinch to implement app to app phone call in my application and it is still not working.
This is my error
FATAL EXCEPTION: main
Process: com.example.thinker.myapplication2, PID: 10039
java.lang.NullPointerException: Attempt to invoke virtual method 'com.sinch.android.rtc.calling.Call com.example.thinker.myapplication2.SinchService$SinchServiceInterface.callUser(java.lang.String)' on a null object reference
at com.example.thinker.myapplication2.tabs.Chatting$Bases.callButtonClicked(Chatting.java:128)
at com.example.thinker.myapplication2.tabs.Chatting$1.onClick(Chatting.java:83)
at android.view.View.performClick(View.java:5265)
at android.view.View$PerformClick.run(View.java:21534)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5683)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
This is my java class.
public class Chatting extends ListActivity {
Runnable refresh, refres;
ImageView send,back,call;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yon);
call= (ImageView)findViewById(R.id.call);
call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (!isOnline(Chatting.this)) {
Toast.makeText(Chatting.this, "No network connection",
Toast.LENGTH_SHORT).show();
return;
}
Bases ba = new Bases();
ba.onServiceConnected();
ba.callButtonClicked();
}
});
}
public class Bases extends BaseActivity {
#Override
protected void onServiceConnected() {
Toast.makeText(this, " call ready", Toast.LENGTH_LONG).show();
}
public void callButtonClicked() {
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(this);
String emaill = sp.getString("friend_email", "anon");
if (emaill.isEmpty()) {
Toast.makeText(this, "Please enter a user to call", Toast.LENGTH_LONG).show();
return;
}
try {
Call call = getSinchServiceInterface().callUser("emaill");
if (call == null) {
// Service failed for some reason, show a Toast and abort
Toast.makeText(this, "Service is not started. Try stopping the service and starting it again before "
+ "placing a call.", Toast.LENGTH_LONG).show();
return;
}
String callId = call.getCallId();
Intent callScreen = new Intent(this, CallScreenActivity.class);
callScreen.putExtra(SinchService.CALL_ID, callId);
startActivity(callScreen);
} catch (MissingPermissionException e) {
ActivityCompat.requestPermissions(this, new String[]{e.getRequiredPermission()}, 0);
}
}
}
}
below is the baseactivity class that has the getSinchServiceInterface(). that is returning null
public abstract class BaseActivity extends Activity implements ServiceConnection {
private SinchService.SinchServiceInterface mSinchServiceInterface;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getApplicationContext().bindService(new Intent(this, SinchService.class), this,
BIND_AUTO_CREATE);
}
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
if (SinchService.class.getName().equals(componentName.getClassName())) {
mSinchServiceInterface = (SinchService.SinchServiceInterface) iBinder;
onServiceConnected();
}
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
if (SinchService.class.getName().equals(componentName.getClassName())) {
mSinchServiceInterface = null;
onServiceDisconnected();
}
}
protected void onServiceConnected() {
// for subclasses
}
protected void onServiceDisconnected() {
// for subclasses
}
protected SinchService.SinchServiceInterface getSinchServiceInterface() {
return mSinchServiceInterface;
}
}
Most of time this happen when someone use wrong way to pass context try to pass context as YourActivityName.this (eg Bases.this )rather than just this or getApplicationContext()
start with
#Override
protected void onServiceConnected() {
Toast.makeText(Bases.this, " call ready", Toast.LENGTH_LONG).show();
}
this is not the proper method to call activity
Bases ba = new Bases();
ba.onServiceConnected();
ba.callButtonClicked();
use
Intent intent = new Intent(YourCurrentActivityName.this,Bases.class);
startActivity(intent);
in the oncreate method you can call this methods callButtonClicked()

Download Manager Cannot resolve getSystemService

I followed a tutorial how to make an App that downloads a .pdf file.
Here's the code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vertretungsplan);
Button dlbutton = (Button) findViewById(R.id.buttondownload);
dlbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(myurl));
request.setTitle("Vertretungsplan");
request.setDescription("wird heruntergeladen");
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
String filename = URLUtil.guessFileName(myurl,null, MimeTypeMap.getFileExtensionFromUrl(myurl));
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS + "Schul-App",filename);
DownloadManager manager =(DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
});
It shows me the error:
Cannot resolve method 'getSystemService(java.lang.string)'
this refers to the object you're working with, since it's inside View.OnClickListener it refers to that object instead of your Activity class.
Something like this should do
final Context c = this;
dlbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//...
DownloadManager manager =(DownloadManager) c.getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
});

Categories

Resources