Error occuring in my Java/Android code on import line - java

I am really new to Android Studio, and am trying to get up to speed. I got some code from the web and I have an errors I know it is because I am referencing a package that is not in my project but how could I resolve this.
The line that has the error is:
import com.androidmkab.randomsplash.MainActivity;
and this is the full code.
package org.quaestio.kotlinconvertedwebview;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.widget.ImageView;
import com.androidmkab.randomsplash.MainActivity;
import java.util.Random;
public class Splashscreen extends Activity {
Thread splashTread;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splashscreen);
imageView = (ImageView)findViewById(R.id.imageView2);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
int[] ids = new int[]{R.drawable.s_img,R.drawable.s_image_black, R.drawable.s_image_black2};
Random randomGenerator = new Random();
int r= randomGenerator.nextInt(ids.length);
this.imageView.setImageDrawable(getResources().getDrawable(ids[r]));
splashTread = new Thread() {
#Override
public void run() {
try {
int waited = 0;
// Splash screen pause time
while (waited < 3500) {
sleep(100);
waited += 100;
}
Intent intent = new Intent(Splashscreen.this,
MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(intent);
Splashscreen.this.finish();
} catch (InterruptedException e) {
// do nothing
} finally {
Splashscreen.this.finish();
}
}
};
splashTread.start();
}
}

So import com.androidmkab.randomsplash.MainActivity means where the MainActivity is located, you need to replace that package with your own. To do this copy your package name(in the top of your activity) and add the activity you want to import, in this case MainActivity.java: import org.quaestio.kotlinconvertedwebview.MainActivity;
Hope it was helpful.

Related

Im new to creating app using java on android studio. Im creating splash screen but not works as i expected

The splash screen should move towards up and down, then go to the next screen. however, it just change the screen normally. the problem i think maybe between the handler and the animate splashscreen. this is my splash.java. hoping anyone can help thank you.
package com.example.dashboard;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.WindowManager;
import android.widget.HeaderViewListAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.airbnb.lottie.LottieAnimationView;
public class Splash extends AppCompatActivity {
private static int SPLASH_TIME_OUT = 3000;
ImageView logo,splashImg;
TextView appName;
LottieAnimationView lottieAnimationView;
Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash);
logo = findViewById(R.id.logo);
appName = findViewById(R.id.appname);
splashImg = findViewById(R.id.img);
lottieAnimationView = findViewById(R.id.lottie);
splashImg.animate().translationY(-1600).setDuration(1000).setStartDelay(3000);
logo.animate().translationY(1400).setDuration(1000).setStartDelay(3000);
appName.animate().translationY(1400).setDuration(1000).setStartDelay(3000);
lottieAnimationView.animate().translationY(1400).setDuration(1000).setStartDelay(3000);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Intent i = new Intent(Splash.this, MainActivity.class);
startActivity(i);
// close this activity
finish();
}
}, SPLASH_TIME_OUT);
}
}
It looks like you start another Activity at the same time you play your animation. Notice the .setStartDelay(3000); at the end of each of your animation calls.
Just removing this will work. However, there are better ways to handle this.
One of the ways would be to override the onAnimationEnd method of your longest animation so that it either changes the Activity immediately or the change is delayed starting from that point in time. This will look something like this:
splashImg.animate().translationY(-1600).setDuration(1000).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
Intent i = new Intent(Splash.this, MainActivity.class);
startActivity(i);
}
});

How to get current wallpaper, change it, then restore it later

I'm struggling with why this code won't compile, I'm trying to get the current wallpaper, then change it, then give the option to change it back.
Below is my code, it doesn't compile because it can't resolve symbol 'context' and it says my drawable cannot be converted to an integer which doesn't make any sense whatsoever.
I'm trying to change the drawable to a bitmap AND I have imported the import
android.content.Context
so what is it I am doing wrong here?? this is my code, the onClick stores the wallpaper and starts the change activity, the onPush method resets the wallpaper and exits the app, any help would be appreciated thanks!
import android.content.Context;
import android.app.Activity;
import android.app.WallpaperInfo;
import android.app.WallpaperManager;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import java.io.IOException;
import static android.app.WallpaperManager.*;
public class SetWallpaperActivity extends Activity {
public Drawable originalWallpaper;
public Bitmap paper1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onClick(View view) {
WallpaperManager wm = WallpaperManager.getInstance(this);
originalWallpaper = wm.getDrawable();
paper1 = BitmapFactory.decodeResource(context.getResources(),
originalWallpaper);
Intent intent = new Intent(
ACTION_CHANGE_LIVE_WALLPAPER);
intent.putExtra(EXTRA_LIVE_WALLPAPER_COMPONENT,
new ComponentName(this, MyWallpaperService.class));
startActivity(intent);
}
public void onPush(View view) {
WallpaperManager wm = WallpaperManager.getInstance(this);
WallpaperInfo wallpaperInfo = wm.getWallpaperInfo();
if (wallpaperInfo != null) {
try {
wm.setBitmap(paper1);
finish();
} catch (IOException e) {
e.printStackTrace();
}
}
finish();
System.exit(0);
}
}
This is the error code I'm getting:
'decodeResource(android.content.res.Resources, int)' in 'android.graphics.BitmapFactory' cannot be applied to '(android.content.res.Resources, android.graphics.drawable.Drawable)'

How to navigate back and resume my app without hanging it?

When I run my code below everything works fine. When I want to go back to the previous activity (using the emulator) I get a black screen and then the app shuts down. I also get a black screen when I exit the application and try to resume it.
The code:
package com.example.bono.as3;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.io.IOException;
import java.io.InputStream;
public class Main extends Activity {
DrawView drawView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
drawView = new DrawView(this);
setContentView(drawView);
}
#Override public void onResume(){
super.onResume();
drawView.resume();
}
#Override public void onPause(){
super.onPause();
drawView.pause();
}
public class DrawView extends SurfaceView implements Runnable{
Thread gameloop = new Thread();
SurfaceHolder surface;
volatile boolean running = false;
AssetManager assets = null;
BitmapFactory.Options options = null;
Bitmap incect[];
int frame = 0;
public DrawView(Context context){
super(context);
surface = getHolder();
assets = context.getAssets();
options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
incect = new Bitmap[2];
try {
for (int n = 0; n < incect.length; n++){
String filename = "incect"+Integer.toString(n+1)+".png";
InputStream istream = assets.open(filename);
incect[n] = BitmapFactory.decodeStream(istream,null,options);
istream.close();
}
} catch (IOException e){
e.printStackTrace();
}
}
public void resume(){
running = true;
gameloop = new Thread(this);
gameloop.start();
}
public void pause(){
running = false;
while (true){
try {
gameloop.join();
}
catch (InterruptedException e){}
}
}
#Override public void run (){
while (running){
if (!surface.getSurface().isValid())
continue;
Canvas canvas = surface.lockCanvas();
canvas.drawColor(Color.rgb(85, 107, 47));
canvas.drawBitmap(incect[frame], 0, 0, null);
surface.unlockCanvasAndPost(canvas);
frame++;
if (frame > 1) frame = 0;
try {
Thread.sleep(500);
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
}
I dont get any error message in the log, what I do get is about 13 messages saying "suspending all threads took: X ms" so it has something to do with my gameloop Thread I think. Unfortunately I don't see what the problem is in my code...
If you need a context, use getApplicationContext() or Activity.this. (seems less buggy with my code)
While going back to a previously used activity, onCreate() is not called, only onResume(), so it might help if you move the following lines to there.
drawView = new DrawView(this);
setContentView(drawView);
Why use inner class at all? Activity is a class already. If you want to use the code multiple times, make it a class on its own.
This is what i use to navigate back. Maybe this is usefull for you 2!
Button backpressed = (Button) findViewById(R.id.btBack);
backpressed.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onBackPressed();
}
});
The onBackPressed() is just a method that you can call if you want to return to the last page.
What it looks like for me:

Android - Buttons: Receiving through data through intents/other methods

E/AndroidRuntime(15518): FATAL EXCEPTION: main
E/AndroidRuntime(15518): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.cydeon.plasmamodz/com.cydeon.plasmamodz.Boots}: java.lang.NullPointerException
E/AndroidRuntime(15518): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2224)
E/AndroidRuntime(15518): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
E/AndroidRuntime(15518): at android.app.ActivityThread.access$600(ActivityThread.java:154)
E/AndroidRuntime(15518): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1248)
E/AndroidRuntime(15518): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(15518): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(15518): at android.app.ActivityThread.main(ActivityThread.java:5235)
E/AndroidRuntime(15518): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(15518): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(15518): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
E/AndroidRuntime(15518): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
E/AndroidRuntime(15518): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(15518): Caused by: java.lang.NullPointerException
E/AndroidRuntime(15518): at android.app.Activity.findViewById(Activity.java:1839)
E/AndroidRuntime(15518): at com.cydeon.plasmamodz.Boots.<init>(Boots.java:47)
E/AndroidRuntime(15518): at java.lang.Class.newInstanceImpl(Native Method)
E/AndroidRuntime(15518): at java.lang.Class.newInstance(Class.java:1319)
E/AndroidRuntime(15518): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
E/AndroidRuntime(15518): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2215)
E/AndroidRuntime(15518): ... 11 more
The topic is confusing. Let me explain. In my app, I have over 70 buttons just for one section. I have many different sections. Now, each button uses the same layout, so each button starts the same activity, that way I don't create 70 seperate classes. Now, in this new class, it must show an image and download a file(when a certain button is clicked) corresponding to the bugton that was picked. So, basically, I need some way to identify those buttons in this other class, and say "if button x was pressed, display image y, if button y was pressed, display image x. Similarly, if button x was pressed, download file y, if button y was pressed, downloa d file x, ect. I just have no idea how to tell which button was pressed in that previous class. I really need help with this. I've been working for 2 weeks and this has put me to a stop, and I cannot find an answer. This isn't really code dependent, and I'll be using this method multiple times throughout the app, so I don't think posting any code is needed. Again, to reiterate my question, multiple buttons start the same activity. In that activity, I need to do stuff according to the button that was pressed in the previous class. Thanks. :)
Edit: Here's some code...
BootFragment.java:
package com.cydeon.plasmamodz;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import com.stericson.RootTools.RootTools;
import com.stericson.RootTools.exceptions.RootDeniedException;
import com.stericson.RootTools.execution.CommandCapture;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class BootFragment extends Fragment {{
//Defining File Directory
File directory = new File(Environment.getExternalStorageDirectory() + "/plasma/boot");
if(directory.exists() && directory.isDirectory()){
//Do nothing. Directory is existent
}else{
//Directory does not exist. Make directory (First time app users)
directory.mkdirs();
}
File bkup = new File(Environment.getExternalStorageDirectory() + "/plasma/boot/bkup");
if(bkup.exists() && bkup.isDirectory()){
//Do nothing. Directory is existent
}else{
//Directory does not exist. Make directory (First time app users)
bkup.mkdirs();
}}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.boot_frag,
container, false);
Button Ablue = (Button) view.findViewById(R.id.bABlue);
Button AblueR = (Button) view.findViewById(R.id.bABlueR);
Button Abokeh = (Button) view.findViewById(R.id.bAbokeh);
Ablue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent b = new Intent(getActivity(), Boots.class);
b.putExtra("Dragon", R.id.bABlue);
BootFragment.this.startActivity(b);
}
});
AblueR.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent c = new Intent(getActivity(), Boots.class);
c.putExtra("Xbox", R.id.bABlueR);
BootFragment.this.startActivity(c);
}
});
Abokeh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent d = new Intent(getActivity(), Boots.class);
d.putExtra("GameB", R.id.bAbokeh);
BootFragment.this.startActivity(d);
}
});
return view;
}}
Boots.java:
package com.cydeon.plasmamodz;
import com.stericson.RootTools.*;
import com.stericson.RootTools.exceptions.RootDeniedException;
import com.stericson.RootTools.execution.CommandCapture;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.concurrent.TimeoutException;
import com.cydeon.plasmamodz.R;
import android.app.ActionBar;
import android.app.Activity;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
//Class for Boot Animation Blue Kindle
public class Boots extends Activity {
public static String TAG = "Boots";
Process process;
private class DownloadFile extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... sURL) {
try{
URL url = new URL(sURL[0]);
URLConnection connection = url.openConnection();
connection.connect();
//Shows 0-100% progress bar
int fileLength = connection.getContentLength();
//Download the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/plasma/boot/b..ootanimation.zip");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
//Publish the Progress
publishProgress((int) (total * 100/fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress){
super.onProgressUpdate(progress);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
mProgressDialog.dismiss();
Context context = getApplicationContext();
CharSequence text = "Installing. Please Wait";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
if (RootTools.isBusyboxAvailable()){
RootTools.remount("/system", "rw");
CommandCapture command = new CommandCapture(0, "su", "sh /sdcard/plasma/scripts/boots.sh");
try {
RootTools.getShell(true).add(command).waitForFinish();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
} catch (RootDeniedException e) {
e.printStackTrace();
}
} else {
RootTools.offerBusyBox(Boots.this);
}
}
}
ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.boots);
ActionBar actionBar = getActionBar();
actionBar.hide();
ImageView img = (ImageView) findViewById(R.id.iv2);
img.setImageResource(R.drawable.boot1);
Button install = (Button) findViewById(R.id.bAInstall);
Button rtrn = (Button) findViewById(R.id.bAReturn);
mProgressDialog = new ProgressDialog(Boots.this);
mProgressDialog.setMessage("Downloading..." );
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
install.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
TextView creator = (TextView) findViewById(R.id.tvCreate);
Intent bootI = getIntent();
int dball = getIntent().getExtras().getInt("Dragon", -1);
int xbox = getIntent().getExtras().getInt("Xbox", -1);
int GameB = getIntent().getExtras().getInt("GameB", 1);
if (dball != -1){
DownloadFile downloadFile = new DownloadFile();
downloadFile.execute("http:\\correspondingurl");
creator.setText("Dragon Ball");
}if (xbox != -1){
DownloadFile downloadFile = new DownloadFile();
downloadFile.execute("http:\\correspondingurl");
creator.setText("Xbox");
}if (GameB != -1){
DownloadFile downloadFile = new DownloadFile();
downloadFile.execute("http:\\correspondingurl");
creator.setText("GameBoy");
}
}
}
);
rtrn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
finish();
}
});
}
}
I have tried many different methods. This is my latest attempt. None of them have worked.
Cat log: Look at the top...
Pass the required information to the new activity in the Intent, via Intent.putExtra()
(see http://developer.android.com/reference/android/content/Intent.html)
You may try assigning each button a unique name/id. When the Button is clicked, retrieve its name and pass it to the new activity using Intent.putExtra(). In new activity, once you have this information, you can perform required function accordingly.
Sample Code :
In the xml for Button, do this
android:onClick="OnButtonClick"
In code of First Activity, defineOnButtonClick as :
public void OnButtonClick(View v) {
switch (v.getId()) {
case R.id.button1:
doSomething1(); //Intent.putExtra(ButtonID)
break;
case R.id.button2:
doSomething2();
break;
}
}
In second Activity, retrieve this ID and have a similar switch-case to perform actions depending on Id of Button.
Hope this makes sense!
In Your fragment class, do the following :
public class BootFragment extends Fragment implements android.view.View.OnClickListener{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
Button Ablue = (Button) view.findViewById(R.id.bABlue);
Button AblueR = (Button) view.findViewById(R.id.bABlueR);
Button Abokeh = (Button) view.findViewById(R.id.bAbokeh);
Ablue.setOnClickListener(this);
AblueR.setOnClickListener(this);
Abokeh.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int btnId = v.getId();
Intent d = new Intent(getActivity(), Boots.class);
d.putExtra("BUTTON_ID", btnId);
startActivity(d);
}
}
In Boots.java, do the following:
public class Boots extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
int btnId = getIntent().getExtras().getInt("BUTTON_ID", -1);
switch(btnId){
case: R.id.your_btn_id_1:
// logic for your button press
break;
case: R.id.your_btn_id_2:
// logic for your button press
break;
case: R.id.your_btn_id_n:
// logic for your button press
break;
}
}
}
Note: You should provide unique id to each button in layout xml file

Change between activities does not work

I'm trying to change between activities in my Android app (2.1-update1), but it doesn't work.
Any suggestions?
The only thing that happens when I debug the app is that it stops on this part of the code in Instrumentation.java:
public void waitForIdle() {
synchronized (this) {
while (!mIdle) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
}
Eclipse says that it is in Thread 1 on
Instrumentation.checkStartActivityResult(int, Object) line: 1537. If I
resume the app, the next stop is in ZygoteInit.java trying to run
Throwable cause = ex.getCause(); ... Eclipse says
ZygoteInit$MethodAndArgsCaller.run() line: 864.
Here is the source code:
HappyHomes.java
package com.example.app;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class HappyHomes extends Activity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button login = (Button) findViewById(R.id.btnLogin);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ProgressDialog laddRuta = ProgressDialog.show(HappyHomes.this, "",
"Loggar in, vänligen vänta...", true);
Intent myIntent = new Intent(view.getContext(), Kategorier.class);
myIntent.
startActivity(myIntent);
}
});
}
}
Kategorier.java
package com.example.app;
import android.app.Activity;
import android.os.Bundle;
public class Kategorier extends Activity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.kategorier);
}
}
Thanks for helping!
Make sure that Kategorier is registered in your AndroidManifest.xml file.
Change myIntent.startActivity(myIntent); to HappyHomes.this.startActivity(myIntent);
There is no any startActivity() method in Intent class . you must be doing wrong.
just write startActivity(myIntent)
All the Services, Broadcast Receivers and Activites must be declared in manifest file.

Categories