Hi,
I am coding an Android app using threads, but the start() function seems to not be recognized and reads: Cannot resolve symbol 'start'.
Here is my code:
Code:
Handler handler = new Handler();
Thread th = new Thread() {
public void run() {
// Asynctask
// delay
handler.postDelayed(this, 1000);
}
};
th.start();
I am new and don't know about this. I have android.os.Handler imported, but the start() is the only thing not working.
Thanks so much!
bump..?
Hello,
You should do
Code:
Thread th = new Thread(new Runnable(){
public void run() {
}
});
th.start();
But if you want a thread to execute periodically:
METHOD 1
Code:
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
MyAsyncTask mAsync = new MyAsyncTask();
mAsync.execute();
}
});
}
};
timer.schedule(task, 0, 1000); //start with a delay of 0 ms and it executes every 1000ms (1 second)
and MyAsyncTask class is:
Code:
private class MyAsyncTask extends AsyncTask<String, Void, String> {
public MyAsyncTask(){
}
@Override
protected String doInBackground(String... params) {
//Background operation in a [B]separate[/B] thread
//Write here your code to run in the background thread
return null;
}
@Override
protected void onPostExecute(String result) {
//Called on Main UI Thread. Executed after the Background operation, allows you to have access to the UI
}
@Override
protected void onPreExecute() {
//Called on Main UI Thread. Executed before the Background operation, allows you to have access to the UI
}
@Override
protected void onProgressUpdate(Void... values) {
//Called on Main UI Thread
}
}
To wait for it to finish:
Code:
try{
if(myAsync!=null){
myAsync.get();
}
}catch(InterruptedException e){
e.printStackTrace();
}catch(ExecutionException e){
e.printStackTrace();
}finally{
myAsync = null;
//Careful. We set null here. So do not reference myAsync again unless you create a new one (myAsync = new ...).
//If you want to reference it again without creating a new one, just delete this line along with the finally block
}
OR
To stop it immediately:
Code:
myAsync.cancel(true);
This stops the myAsync. Timer will still be creating and executing a new AsyncTask. To stop that:
Code:
timer.cancel(); // Terminates this timer, discarding any currently scheduled tasks.
timer.purge(); // Removes all cancelled tasks from this timer's task queue.
NOTE: If you execute the timer.cancel(), then you cannot use the same timer again. You need to create a new one like this:
Code:
timer = new Timer();
task = new TimerTask()..........
To learn more about AsyncTask, take a look here
METHOD 2
Code:
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
// do stuff
}
}, 0, 1, TimeUnit.SECONDS); //Start with a delay of 0 seconds and repeat every 1 second.
To stop the thread use:
Code:
exec.shutdown(); //It will not be executed any more, but the task that the thread is already doing will not be interrupted.
OR
Code:
exec.shutdownNow(); //It will interrupt the current work of the thread being running, and also prevents the thread from running periodically again.
If you have any further questions please let me know
Related
I am trying to develop a register system in Android studio, however it registers users but the application closes down as it gives java.lang.NullPointerException error.
Errro Messages
> E/JSON Parser﹕ Error parsing data org.json.JSONException: Value
> 2015-12-09 of type java.lang.String cannot be converted to JSONObject
>
> E/AndroidRuntime﹕ FATAL EXCEPTION: mainPID: 2386
> java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on
> a null object reference
Code:
> at com.bradvisor.bradvisor.Register$ProcessRegister.onPostExecute(Register.java:214)
if (json.getString(KEY_SUCCESS) != null) { - Line 214: where I get an error message, not to sure why
> at com.bradvisor.bradvisor.Register$ProcessRegister.onPostExecute(Register.java:171)
private class ProcessRegister extends AsyncTask<String, String, JSONObject> { - Line 171: where I get an error message, not to sure why.
Register.java File.
Code:
private class ProcessRegister extends AsyncTask<String, String, JSONObject> { - Line 171: where I get an error message, not to sure why.
/**
* Defining Process dialog
**/
private ProgressDialog pDialog;
String email,password,fname,lname,uname;
@Override
protected void onPreExecute() {
super.onPreExecute();
inputUsername = (EditText) findViewById(R.id.uname);
inputPassword = (EditText) findViewById(R.id.pword);
fname = inputFirstName.getText().toString();
lname = inputLastName.getText().toString();
email = inputEmail.getText().toString();
uname= inputUsername.getText().toString();
password = inputPassword.getText().toString();
pDialog = new ProgressDialog(Register.this);
pDialog.setTitle("Contacting Servers");
pDialog.setMessage("Registering ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected JSONObject doInBackground(String... args) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(fname, lname, email, uname, password);
return json;
}
@Override
protected void onPostExecute(JSONObject json) {
/**
* Checks for success message.
**/
try {
if (json.getString(KEY_SUCCESS) != null) { - Line 214: where I get an error message, not to sure why.
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
String red = json.getString(KEY_ERROR);
if(Integer.parseInt(res) == 1){
pDialog.setTitle("Getting Data");
pDialog.setMessage("Loading Info");
registerErrorMsg.setText("Successfully Registered");
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
/**
* Removes all the previous data in the SQlite database
**/
UserFunctions logout = new UserFunctions();
logout.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_FIRSTNAME),json_user.getString(KEY_LASTNAME),json_user.getString(KEY_EMAIL),json_user.getString(KEY_USERNAME),json_user.getString(KEY_UID),json_user.getString(KEY_CREATED_AT));
/**
* Stores registered data in SQlite Database
* Launch Registered screen
**/
Intent registered = new Intent(getApplicationContext(), Registered.class);
/**
* Close all views before launching Registered screen
**/
registered.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pDialog.dismiss();
startActivity(registered);
finish();
}
else if (Integer.parseInt(red) ==2){
pDialog.dismiss();
registerErrorMsg.setText("User already exists");
}
else if (Integer.parseInt(red) ==3){
pDialog.dismiss();
registerErrorMsg.setText("Invalid Email id");
}
}
else{
pDialog.dismiss();
registerErrorMsg.setText("Error occured in registration");
}
} catch (JSONException e) {
e.printStackTrace();
}
}}
public void NetAsync(View view){
new NetCheck().execute();
}}
deleted
Are you sure the object returned from doInBackground is not null ?
@override
protected JSONObject doInBackground(String... args) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(fname, lname, email, uname, password);(json is null)
return json; ( return null )
}
@override
protected void onPostExecute(JSONObject json) { ( json is null )
/**
* Checks for success message.
**/
try {
if (json.getString(KEY_SUCCESS) != null) { - Line 214: where I get an error message, not to sure why. ( null getString cause exception )
i work with this guild: Android Uploading Camera Image, Video to Server with Progress Bar
and when i take image i got this error:
Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/Pictures/profile_imagephoto.jpg: open failed: ENOENT (No such file or directory
What can i do to fix this?
Code:
//Upload Profile Image
profileImage.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
pictureCheck = "to_profile";
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setIcon(R.drawable.ic_action_search);
builder.setMessage("Select What To Do:")
// Positive button functionality
.setPositiveButton("Camera",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int arg0) {
Toast.makeText(MainActivity.this, "Open Camera...", Toast.LENGTH_SHORT).show();
Intent cameraintent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraintent, IMAGE_CAPTURE);
}
})
// Negative button functionality
.setNegativeButton("Gallery",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int arg0) {
Toast.makeText(
MainActivity.this, "Open Gallery...", Toast.LENGTH_SHORT).show();
// Do more stuffs
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//dialog.cancel();
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
galleryIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(galleryIntent, RESULT_LOAD_INAGE);
}
});
// Create the Alert Dialog
AlertDialog alertdialog = builder.create();
// Show Alert Dialog
alertdialog.show();
}
});
/**
* Here we store the file url as it will be null after returning from camera
* app
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
@Override
public void onActivityResult(int requestCodeToProfile, int resultCodeToProfile, Intent dataToProfile) {
super.onActivityResult(requestCodeToProfile, resultCodeToProfile, dataToProfile);
launchUploadActivity(true);
}
private void launchUploadActivity(boolean isImage){
Intent i = new Intent(MainActivity.this, UploadActivity.class);
i.putExtra("filePath", fileUri.getPath());
i.putExtra("isImage", isImage);
startActivity(i);
}
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir =
new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"profile_image");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "Oops! Failed create "
+ "profile_image" + " directory");
return null;
}
}
// Create a media file name
java.util.Date date= new java.util.Date();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(date.getTime());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + "photo.jpg");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
This is a long shot, but the path of your image looks wrong. Are you missing a slash between the last dir and 'photo.jpg'. Should be this line:
mediaFile = new File(mediaStorageDir.getPath() + "photo.jpg");
SU Version 2.82 and using BlueStacks 3
I've made a post on StackExchange but w/o any responses - inside are links I'll reference below but unfortunately can't directly post here due to being a new user of these forums. Googling the following should turn up the result: SU Command to start java class for input automation not working
Since then I've learned a bit more about what I'm trying to do (which is surprising considering I've been attempting this since the 30th of January) and implemented a singleton so that I can toast from within the class I'm attempting to start. Regardless of whether this allows me to inject inputs to other apps, my current problem is simply that I'm unable to use a SU command to open up my Main.Java class as described in the following links:
The code describing what I'm trying to do: OmerJerk Execute Java Class as Root User
The code w/ a full implementation: Remotedroid on GitHub
^ ServerService runs MainStarter which runs Main.Java as SU so that Main.Java can run EventInput to inject motion events
The super basic implementation I've got is below, but I've tried a bunch of things. I can't seem to figure out what's going wrong.
A snippet from ActivityMain wherein I'm running the Main.Java (attempting at least):
Code:
new Main().main(COMMAND3); //COMMAND3 is just a String[] because if it's not provided this won't execute. This isn't what I'm trying to do, though. Just a test to see if my Main.Java was broke.
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids){
try {
//BlueStacks is 32 bit so it only has app_process - it doesn't have app_process32 and I believe if you try to target it it simply fails (the symbolic link is inconsistent iirc) vv
String[] COMMAND4 = {"su", "-c", "\"CLASSPATH=" + MainActivity.this.getPackageCodePath(), "/system/bin/app_process", "/system/bin", MainActivity.this.getPackageName() + ".Main"};
java.lang.Process console = Runtime.getRuntime().exec(COMMAND4);
BufferedWriter stdin = new BufferedWriter(new OutputStreamWriter(console.getOutputStream()));
String outputStr = new String();
BufferedReader reader = new BufferedReader(new InputStreamReader(console.getInputStream()));
while (reader.ready()) {
outputStr += reader.readLine();
}
PropertyReader.getInstance().setText(outputStr);
} catch (IOException e) {
e.printStackTrace();
PropertyReader.getInstance().showToast("IOException" + e.getMessage());
}
// final List<String> SUOutput = Shell.SU.run(String.format(COMMAND,
// new String[] {
// getApplicationContext()
// }));
// final String joined = TextUtils.join(", ", SUOutput);
//
// runOnUiThread(new Runnable() {
// @Override
// public void run() {
// if (SUOutput != null) {
// Toast.makeText(MainActivity.this, "Output isn't null" + joined, Toast.LENGTH_LONG).show();
// Toast.makeText(MainActivity.this, joined, Toast.LENGTH_LONG).show();
// Toast.makeText(MainActivity.this, SUOutput.toString(), Toast.LENGTH_LONG).show();
//
// } else {
// Toast.makeText(MainActivity.this, "Output is null o-o", Toast.LENGTH_LONG).show();
// }
// }
// });
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "It finished.. ?", Toast.LENGTH_LONG).show();
PropertyReader.getInstance().ToastString();
}
});
return null;
}
}.execute();
}
And my Main.Java is reaaaally simple and very stripped down at this point:
Code:
package intsumniac.overbitegames.com.intsumniac;
import android.os.Process;
public class Main {
public static void main(String[] args) {
PropertyReader.getInstance().showToast("Main Is working!!! SUCCESS" + "current process id = " + Process.myPid() + "current process uid = " + Process.myUid()); //Should be 0, preferably
}
}
It is certainly possible to run Java stuff as root, however you are lacking many contexts/instances/etc. There is some trickery to be able to get around some of that. Some of my apps' root parts are mostly Java, in fact.
Rule of thumb is that most Android API calls are not available, just standard Java things. Toasting for example is most certainly not available.
Hey guys.
So, I've spent the last two days watching every tutorial about working with sqlite, but I'm doing something wrong and can't find out what.
The app is done, only needs the SQLite part, Its basicly a webapp with favorites.
Altough I have changed the code several times, this is what I ended up with:
DBManager.java
<code>
package com.rjpf.mywebapps;
import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class DBManager
{
private DbHelper dbHelper;
private Context context;
private SQLiteDatabase database;
public DBManager(Context c)
{
context=c;
}
public DBManager open() throws SQLException
{
dbHelper = new DbHelper(context);
database = dbHelper.getWritableDatabase();
return this;
}
public void close()
{
dbHelper.close();
}
public void insert(String name, String url)
{
ContentValues contentValue = new ContentValues();
contentValue.put(DbHelper.CONTACTS_COLUMN_NAME, name);
contentValue.put(DbHelper.CONTACTS_COLUMN_URL, url);
database.insert(dbHelper.CONTACTS_TABLE_NAME, null, contentValue);
}
}
</code>
When I try to call it in the main activity with:
MainActivity.java
<code>
(...)
private LinearLayout Layout_Add;
private TextView TxT_add_nomE;
private TextView TxT_add_urL;
private Button Button_Add_to_DB;
private Button btn_BACK_Add;
DbHelper myDB;
(...)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myDB = new DbHelper(this);
(...)
Button_Add_to_DB.setOnClickListener(new View.OnClickListener() {
@override
public void onClick(View view) {
Add_ItemToDb();
}
});
(...)
public void Add_ItemToDb()
{
if (TxT_add_nomE.getText().toString().trim().length() == 0 || TxT_add_urL.getText().toString().trim().length() == 0)
{
TxT_add_nomE.setText("Please don't leave fields empty!");
return;
}
else
{
String addNome = TxT_add_nomE.getText().toString();
String addUrl = TxT_add_urL.getText().toString();
// ADD TO DB
DBManager DataManager = new DBManager(this);
DataManager.insert(addNome,addUrl); // This line is what gives the error, when I click the button to add the App craches
TxT_add_nomE.setText("Name");
TxT_add_urL.setText("Url");
}
}
</code>
Thanks in advance and sorry for the long post, This is my first app and also the first time in java
Goodmorning, I've tried to implement the method that request permission first and than execute something but without success ...
Here is my MainActivity code:
Code:
public class MainActivity extends AppCompatActivity {
public static String latitudineCorrente = ""; //current Latitude
public static String longitudineCorrente = ""; //current Longitude
private SharedPreferences sharedPreferences; //shared preferences
private SharedPreferences.Editor mEditor; // shared preferences editor
/* Variable for getting location */
private FusedLocationProviderClient fusedLocationProviderClient;
private LocationRequest locationRequest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String appLanguage = "ita";
LanguageUtil.setAppLanguage(getApplicationContext(), appLanguage);
/* .... other code.... */
sharedPreferences = this.getSharedPreferences("appname", MODE_PRIVATE);
mEditor = sharedPreferences.edit(); // set edit sharedpreferences
richiamaPermessi(); //permission request
requestLocationUpdates(); // function requestlocationupdates();
CaricamentoInizialeApplicazione(); // function for presetting configurations
}
private void CaricamentoInizialeApplicazione() {
boolean configIniziale = sharedPreferences.getBoolean("configurazioneinizialeok", false);
if(!configIniziale)
{
/* can't execute this because Double.parseDouble(this.latitudineCorrente), Double.parseDouble(this.longitudineCorrente) */
ApiMarkers.getMarkers(MainActivity.this, 0, 400,
Double.parseDouble(this.latitudineCorrente), Double.parseDouble(this.longitudineCorrente),
0, 0,0,1, 0,0,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
/* response elaborations */
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
Toast.makeText(MainActivity.this, "" + error.getMessage(), Toast.LENGTH_LONG).show();
error.printStackTrace();
}
});
mEditor.putBoolean("configurazioneinizialeok", true);
mEditor.commit();
}
}
/* Function for requist location updates */
public void requestLocationUpdates() {
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) ==
PermissionChecker.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) ==
PermissionChecker.PERMISSION_GRANTED) {
fusedLocationProviderClient = new FusedLocationProviderClient(this);
locationRequest = new LocationRequest();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setFastestInterval(1500);
locationRequest.setInterval(3000);
fusedLocationProviderClient.requestLocationUpdates(locationRequest, new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
mEditor = sharedPreferences.edit();
mEditor.putString("latitudine", String.valueOf(locationResult.getLastLocation().getLatitude()));
mEditor.putString("longitudine", String.valueOf(locationResult.getLastLocation().getLongitude()));
MainActivity.latitudineCorrente = String.valueOf(locationResult.getLastLocation().getLatitude());
MainActivity.longitudineCorrente = String.valueOf(locationResult.getLastLocation().getLongitude());
Log.d("coordinate", "MAIN ACTIVITY: Latitudine: " + MainActivity.latitudineCorrente + "/"
+ "Longitudine: " + MainActivity.longitudineCorrente);
}
}, getMainLooper());
} else richiamaPermessi();
}
/* Function for requesting access */
public void richiamaPermessi()
{
Permissions.check(this, new String[] { Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION},
"Permessi di locazione obbligatori per determinare la propria posizione!",
new Permissions.Options().setSettingsDialogTitle("Avviso").setRationaleDialogTitle("Permessi locazione"),
new PermissionHandler() {
@Override
public void onGranted() {
requestLocationUpdates();
}
@Override
public void onDenied(Context context, ArrayList<String> deniedPermissions) {
super.onDenied(context, deniedPermissions);
richiamaPermessi();
}
});
}
}
The problem is executing function ApiMarkers.getMarkers(.... with latitude and longitude filled ...) but can't execute because latitude and longitude are not loaded... I spent two nights without solution Thanks for any help! Cristian
Up! I tried to follow this video on youtube youtube.com/watch?v=gEcFf2Mv4L0 and in any case I could not understand where or when I can call the method "CaricamentoInizialeApplicazione ()" in order to call a method that uses the location coordinates! What I want is to make sure that I don't call the method already said until the location coordinates are loaded into the variables indicated in the code! Is it possible that someone is not able to solve the problem? Thank you
Oh thanks for any help!