Download Manager Cannot resolve getSystemService - java

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);
}
});

Related

OkHttpClient throws an error when trying to load data from sharedPrefrences

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.

nullpointerexception error I do now know how to fix

where is error? how can I fix it? layout is true error in 24th line that
kaleciKayit.setOnClickListener(new View.OnClickListener() {
here is my all codes
public class oyuncuAdlariActivity extends AppCompatActivity {
Button kaleciKayit;
Button oyuncuKayit;
EditText isimGiris;
String isimGirisString;
int kaleciSayisi = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_oyuncu_adlari);
kaleciKayit = (Button) findViewById(R.id.kaleciButton);
oyuncuKayit = (Button) findViewById(R.id.oyuncuButton);
isimGiris = (EditText) findViewById(R.id.isimGir);
kaleciKayit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
kaleciSayisi++;
isimGirisString = isimGiris.getText().toString();
if (isimGirisString.isEmpty()){
Toast toast1 = Toast.makeText(getApplicationContext(),getApplicationContext().getString(R.string.isimBos), Toast.LENGTH_SHORT);
toast1.show();
}
else if (kaleciSayisi >2)
kaleciKayit.setEnabled(false);
}
});
}
}
First of all, I will recommend setting the objects in a class to private. I think the problem is that maybe you are assigning the id of the wrong widget? check the FindViewByID again.
The other 3 possibilities that I can think about are-
The problem is in the first activity(In this case I ask you to post here the content of the first activity)
The setContentView method points at a wrong XML file.
Your AVD ran out of memory and you need to add more to it in the AVD Manager tool.
Change MainActivity to this,
public class MainActivity extends AppCompatActivity {
Button devamButton;
EditText takim1, takim2;
String takimTextA;
String takimTextB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
devamButton = findViewById(R.id.devamButton);
takim1 = findViewById(R.id.takimB);
takim2 = findViewById(R.id.takimA);
devamButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
takimTextA = takim1.getText().toString();
takimTextB = takim2.getText().toString();
if (takimTextA.equals(takimTextB)) {
Toast toast1 = Toast.makeText(getApplicationContext(),getApplicationContext().getString(takimAyniOlmaz), Toast.LENGTH_SHORT);
toast1.show();
} else if (takimTextA.isEmpty() || takimTextB.isEmpty()) {
Toast toast2 = Toast.makeText(getApplicationContext(), getApplicationContext().getString(R.string.takimBosBirakma), Toast.LENGTH_SHORT);
toast2.show();
} else {
activityGecis1(v);
}
}
});
}
private void activityGecis1(View v) {
Intent gecis1 = new Intent(v.getContext(), oyuncuAdlariActivity.class);
startActivity(gecis1);
}
Since you are calling inside onclicklistener maybe this in intent may point to that functions class.

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

Destroy data on pressing back button in android

I have few activity files that contains almost same code as shown below. Well i have not included onDestroy and finish() method in all of my activity files, before moving forward i want to be sure of the code posted below.
public class Three extends AppCompatActivity {
Button forwardB,backwardB,homeB;
TextView textView2,textView4,textView5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.one);
//Place advertisement here
AdView adView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.build();
adView.loadAd(adRequest);
//
//find widget by Id
forwardB = (Button) findViewById(R.id.forwardB);
backwardB = (Button) findViewById(R.id.backwardB);
homeB = (Button) findViewById(R.id.homeB);
textView2= (TextView) findViewById(R.id.textView2);
textView4 = (TextView) findViewById(R.id.textView4);
textView5 = (TextView) findViewById(R.id.textView5);
textView5.setText("3/50");
//set text inside textView3 and textView4
textView2.setText("Apfel");textView4.setText("apple");
//set on click listener for forward,backward and home button
forwardB.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), Two.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
finish();
}
});
homeB.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
finish();
}
});
backwardB.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), Four.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
finish();
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
After running the application i found a serious issue with data,it looks like android keeps data in background. How can i avoid this?
Everytime i run app and check the data it seems to be increasing.
Well this is my MainActivity.java:
public class MainActivity extends Activity {
Button btnflashcards;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
//create widget ids that are usable forw rest of the code
btnflashcards = (Button) findViewById(R.id.btnflashcards);
}
//on flash card button click
public void findFlashCards(View v){
Intent i = new Intent(this, FlashCardSelection.class);
startActivity(i);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
You will need to explicitly clear the application's user data every time you exit the aplication or at any point of time you want to during the use of your app.
Use this: ActivityManager's clearApplicationUserData() method
As per documentation this will:
Permits an application to erase its own data from disk. This is
equivalent to the user choosing to clear the app's data from within
the device settings UI. It erases all dynamic data associated with the
app -- its private data and data in its private area on external
storage -- but does not remove the installed application itself, nor
any OBB files.
Give something like this a shot
import java.io.File;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
public class HelloWorld extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle *) {
super.onCreate(*);
setContentView(R.layout.main);
}
#Override
protected void onStop(){
super.onStop();
}
//Fires after the OnStop() state
#Override
protected void onDestroy() {
super.onDestroy();
try {
trimCache(this);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void trimCache(Context context) {
try {
File dir = context.getCacheDir();
if (dir != null && dir.isDirectory()) {
deleteDir(dir);
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}
}

How can i use Create Chooser on button click inside a subclass of dialog

Using this code to share audio file through create chooser but not working...
public class ActionDialog extends Dialog {
static String sSongTitle="";
static String sSongPath = "";
static File fSongFile ;
public ActionDialog(final Context context, Message response) {
super(context);
// Inflate our UI from its XML layout description.
setContentView(R.layout.after_save_action);
setTitle(R.string.alert_title_success);
((Button)findViewById(R.id.button_share))
.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Uri StringUri = Uri.fromFile(new File(sSongPath));
Intent intent = new Intent(android.content.Intent.ACTION_SEND, StringUri);
Intent in = new Intent(android.content.Intent.ACTION_SEND, StringUri, context, null);
intent.setType("audio/*");
startActivity(Intent.createChooser(in, "select any from the list:"));//getting error here as create method startActivity(Intent)
}
});
}
}
your Intent is intent not ishare
Uri is stringUri but you mention ed as StringUri..
can you post entire code.. to see errors if any
see this
code
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((Button) findViewById(R.id.button_share))
.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Uri stringUri = Uri.fromFile(new File(""));
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);// intent for sharing
sendIntent.putExtra(Intent.EXTRA_TEXT, stringurl);
sendIntent.setType("audio/*");
sendIntent.putExtra(Intent.EXTRA_SUBJECT, StringTitle);
startActivity(sendIntent);// getting error
// as create
// method
// startActivity(Intent)
}
});
}

Categories

Resources