why i get error when i define new intent? - java

package islam.work;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.content.Intent;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
public class Tasbeeeee7_IslamicActivity extends Activity {
MediaPlayer begin;
Intent inti;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
begin = MediaPlayer.create(Tasbeeeee7_IslamicActivity.this, R.drawable.media);
begin.start();
Thread timer = new Thread(){
public void run(){
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
finally
{
inti = new Intent(this, program.class); //error here
startActivity(inti);
}
}
};
timer.start();
}
}

Change
inti = new Intent(this, program.class);
to
inti = new Intent(Tasbeeeee7_IslamicActivity .this, program.class);
Since you are constructing your Intent inside of a Thread, this is referring to the Thread instead of your Activity Context.

Related

How to unzip password protected zip files in android studio?

I tried unzipping a zip file with password But it goes to a dead end. Like It says No read permission. I requested the permission from the code and allowed in app. Still error coming
Error - net.lingala.zip4j.exception.ZipException: no read access for the input zip file
This is the code
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.ZipFile;
public class MainActivity2 extends AppCompatActivity {
;
private FileChooserFragment fragment;
private Button buttonShowInfo;
Context context;
String vv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.buttonShowInfo = this.findViewById(R.id.button_showInfo);
this.buttonShowInfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
showInfo();
} catch (ZipException e) {
e.printStackTrace();
}
}
});
}
private void showInfo() throws ZipException {
try {
//
System.out.println(Environment.getExternalStorageDirectory().toString());
ZipFile zipFile = new ZipFile("/storage/emulated/0/Download/1.zip);
if (zipFile.isEncrypted()) {
zipFile.setPassword("aa".toCharArray());
}
zipFile.extractAll(Environment.getExternalStorageDirectory().toString());
break;
} catch (ZipException e) {
System.out.println("nope");
e.printStackTrace();
}
}}
Password is aa
Please give me a code which works in new version of android studio and android 11 atleast

Android OnPrimaryClipChangedListener in service not working outside app

I try to develop an app in java,
I try to get all clipboard statement whatever inside the app or when the app closed (home button pressed )
I tried a lot of things after searching on the internet but I don't get anything excepted this problem happen with SDK >= 26
------------ steps I do ----------
create service
define service in the manifest file
create a notification channel
start service by (startForeground)
NOTE: THIS WORKING VERY WELL IF I COPY INSIDE APP
----------------------------------------- ClipboardMonitorService.java
package com.example.testclipboard;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.Date;
/**
* Monitors the {#link ClipboardManager} for changes and logs the text to a file.
*/
public class ClipboardMonitorService extends Service {
private ExecutorService mThreadPool = Executors.newSingleThreadExecutor();
private ClipboardManager mClipboardManager;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onCreate() {
super.onCreate();
//startForeground();
// TODO: Show an ongoing notification when this service is running.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
startMyOwnForeground();
else
startForeground(1, new Notification());
//mHistoryFile = new File(Environment.getExternalStorageDirectory(), FILENAME);
mClipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
mClipboardManager.addPrimaryClipChangedListener(
mOnPrimaryClipChangedListener);
Log.i("Service Created ","Yes Created !");
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void startMyOwnForeground(){
String NOTIFICATION_CHANNEL_ID = "com.example.testclipboard";
String channelName = "My Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
//.setSmallIcon(R.drawable.icon_1)
.setContentTitle("App is running in background")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(2, notification);
}
#Override
public void onDestroy() {
super.onDestroy();
if (mClipboardManager != null) {
mClipboardManager.removePrimaryClipChangedListener(
mOnPrimaryClipChangedListener);
}
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
private ClipboardManager.OnPrimaryClipChangedListener mOnPrimaryClipChangedListener =
new ClipboardManager.OnPrimaryClipChangedListener() {
#Override
public void onPrimaryClipChanged() {
String _string =mClipboardManager.getPrimaryClip().getItemAt(0).getText().toString();
logger(_string);
ClipData clip = mClipboardManager.getPrimaryClip();
mThreadPool.execute(new WriteHistoryRunnable(
clip.getItemAt(0).getText()));
}
};
private void logger(String txt){
Log.i("Logger : " , txt);
}
private class WriteHistoryRunnable implements Runnable {
private final CharSequence mTextToWrite;
public WriteHistoryRunnable(CharSequence text) {
mTextToWrite = text;
}
#Override
public void run() {
if (TextUtils.isEmpty(mTextToWrite)) {
// Don't write empty text to the file
return;
}
Log.i("Copyed : ",mTextToWrite.toString() );
String clipboared = mTextToWrite.toString();
//writer.newLine();
//writer.close();
}
}
}
--------------------------------------- MainActivity.java
package com.example.testclipboard;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ActivityManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.hbb20.CountryCodePicker;
public class MainActivity extends AppCompatActivity {
private Intent forService;
ClipboardManager myClipBoard ;
Button btnClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
forService = new Intent(MainActivity.this,TestSmallService.class);
btnClick = (Button)findViewById(R.id.btntest);
btnClick.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onClick(View view) {
Log.i("Btn Clicked ","Heyys");
// ToDO : The Old One
Intent intent = new Intent(getBaseContext(), ClipboardMonitorService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
getBaseContext().startForegroundService(intent);
} else {
getBaseContext().startService(intent);
}
}
});
}
}```

Where is this LoginActivity retrieving phoneno. and password from?

The LoginActivity.java is the first thing that gets run after I open the android app and a login screen is seen asking for phonenumber and password which it retrieves from a database. I have a mysql database related to this project running in my computer but how do I find exactly from where in the database the app is retrieving the phoneno. and password from?
LoginActivity.java
package com.example.ankit.mrestro.Controller;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.squareup.otto.Subscribe;
import com.example.ankit.mrestro.Bus.BusProvider;
import com.example.ankit.mrestro.Bus.LoginEvent;
import com.example.ankit.mrestro.Bus.LoginSuccessEvent;
import com.example.ankit.mrestro.Bus.PushRegisterEvent;
import com.example.ankit.mrestro.R;
import com.example.ankit.mrestro.model.LoginResult;
import com.example.ankit.mrestro.services.DataService;
import com.example.ankit.mrestro.services.RESTrepository;
public class LoginActivity extends Activity {
public static final String PREF_ACCOUNT_ID = "cust_id";
public static final String PREF_TOKEN = "accessToken";
public static final String SHARED_PREF_DB_NAME = "loginResult";
private ProgressDialog progressDialog;
public static Intent createIntent(Context c) {
return new Intent(c, LoginActivity.class);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DataService.init();
progressDialog = new ProgressDialog(this);
/**
* Check either we are already logged in
*/
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF_DB_NAME, 0);
if (sharedPreferences.getString(PREF_TOKEN, "").length() != 0) {
RESTrepository.setToken(sharedPreferences.getString(PREF_TOKEN, ""));
RESTrepository.setUser_id(sharedPreferences.getInt(PREF_ACCOUNT_ID, 0));
goToMainActivity();
}
setContentView(R.layout.activity_login);
PushManager.startWork(getApplicationContext(), PushConstants.LOGIN_TYPE_API_KEY,
"hwfeocSIPlgKTasIuARPREnS");
//SharedPreferences preferences=getSharedPreferences("pushService",0);
//String userId=preferences.getString("user_id","no data");
//Toast.makeText(this,"user id is:"+userId,Toast.LENGTH_SHORT).show();
Button loginButton=(Button)findViewById(R.id.email_sign_in_button);
loginButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
String phoneno=((TextView)findViewById(R.id.email)).getText().toString();
String password=((TextView)findViewById(R.id.password)).getText().toString();
// Toast.makeText(getBaseContext(),"login..."+phoneno+"..."+password,Toast.LENGTH_SHORT).show();
progressDialog.show();
BusProvider.get().post(new LoginEvent(phoneno,password));
}
});
}
#Override
protected void onResume(){
super.onResume();
BusProvider.get().register(this);
}
#Override
protected void onPause(){
super.onPause();
BusProvider.get().unregister(this);
}
#Subscribe
public void onLoginSuccessEvent(LoginSuccessEvent loginSuccessEvent){
progressDialog.hide();
LoginResult result=loginSuccessEvent.getResult();
if (result != null) {
// Toast.makeText(this,result.getCust_id()+result.getCust_name()+result.getCust_access_token(),Toast.LENGTH_SHORT).show();
//Toast.makeText(this,"Login Success",Toast.LENGTH_SHORT).show();
SharedPreferences preferences = this.getSharedPreferences(SHARED_PREF_DB_NAME, MODE_PRIVATE);
preferences.edit().putString(PREF_TOKEN,result.getCust_access_token()).commit();
preferences.edit().putInt(PREF_ACCOUNT_ID,result.getCust_id()).commit();
SharedPreferences pushPreferences=this.getSharedPreferences("pushService",0);
BusProvider.get().post(new PushRegisterEvent
(result.getCust_id(),result.getCust_access_token(),pushPreferences.getString("user_id","")));
goToMainActivity();
} else {
Toast.makeText(this, "Unable to login, please retry", Toast.LENGTH_SHORT).show();
}
}
private void goToMainActivity() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
}
In Login Activity your on button click your are getting the the phone number and password of your sending it to the server and onLoginSuccessEvent you are getting your response and save it to the sharePreferences

i have made a simple music player app but it does not play music from sdcard it is working when i use it for playing a song from res/raw

This is my code for the MainActivity. I am using only one activity:
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.IOException;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button bPlay,bStop;
public static MediaPlayer mplayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bPlay=(Button)findViewById(R.id.button);
bStop=(Button)findViewById(R.id.button2);
bPlay.setOnClickListener(this);
bStop.setOnClickListener(this);
}
#Override
public void onClick(View v){
switch(v.getId()){
case R.id.button:
String path = "/sdcard/honey.mp3";
//bStop.setText(path);
// Uri myUri = Uri.parse("file:///storage/emulated/0/honey.mp3/");
//Uri myUri = Uri.parse("android.resource://com.example.shubhamchauhan.mediaplayer/"+R.raw.honey);
mplayer = new MediaPlayer();
mplayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try{
mplayer.setDataSource(path);
}catch(IllegalArgumentException e){
Toast.makeText(getApplicationContext(),"You set wrong uri",Toast.LENGTH_SHORT).show();
}catch(SecurityException e){
Toast.makeText(getApplicationContext(),"You set wrong uri",Toast.LENGTH_SHORT).show();
}catch(IllegalStateException e){
Toast.makeText(getApplicationContext(),"You set wrong uri",Toast.LENGTH_SHORT).show();
}catch(IOException e){
Toast.makeText(getApplicationContext(),"You set wrong uri start",Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
try {
mplayer.prepare();
}catch(IllegalStateException e){
Toast.makeText(getApplicationContext(),"You set wrong uri",Toast.LENGTH_SHORT).show();
}catch(IOException e){
Toast.makeText(getApplicationContext(),"You set wrong uri prepare",Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
mplayer.start();
break;
case R.id.button2:
if(mplayer!=null && mplayer.isPlaying()){
mplayer.stop();
}
break;
}
}
}
How to fix it?

Android - Threads not executing

So yeah, my thread isn't executing, or doing the code within it. I just wanted to run a shell script from my sdcard, and show a "loading" circles or "progress" circle or whatever you want to call it. When I click the button to run the thread, I get the progress/loading bar/circle, but it just sits there and does nothing. I've looked at some examples but still cannot figure out what I did wrong. Here's my code:
package com.cydeon.plasmamodz;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeoutException;
import com.stericson.RootTools.*;
import com.stericson.RootTools.exceptions.RootDeniedException;
import com.stericson.RootTools.execution.CommandCapture;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Install extends Activity{
private static ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.install);
Button bInstall = (Button) findViewById(R.id.bInstallTheme);
bInstall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
showDialog();
}
});
}
public void showDialog(){
progressDialog = ProgressDialog.show(Install.this, "", "Installing Theme", true);
Thread thread = new Thread();
thread.start();
}
public void run(){
try{
Thread.sleep(1000);
CommandCapture command = new CommandCapture(0, "su", "sh /sdcard/plasma/scripts/install.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();
}
}catch (InterruptedException e){
e.printStackTrace();
}
handler.sendEmptyMessage(0);
}
private static Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
progressDialog.dismiss();
}
};
}
So, am I doing something wrong? Why won't it run my code? Thanks!
The thread doesn't know what to run. Change
public class Install extends Activity{
to
public class Install extends Activity implements Runnable {
and change
Thread thread = new Thread();
to
Thread thread = new Thread(this);

Categories

Resources