Continuously outputting index of an array - java

I have an array that I want to output each index continuously and randomly
here is my code :
package com.example.testtingskripsi;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public String [] ArrayA ={"80","81","82","83","84","85"};
public TextView mViewLabel;
#Override
protected void onCreate(Bundle savedInstanceState) {
int rando =(int) ((Math.random())*ArrayA.length);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewLabel = (TextView) findViewById(R.id.textChanger);
Button startHeartbeat = (Button) findViewById(R.id.start);
Button stopHeartbeat = (Button) findViewById(R.id.stop);
startHeartbeat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
for(int mIfCounter = 0;mIfCounter<ArrayA.length-1;mIfCounter++){
mViewLabel.setText(ArrayA[mIfCounter]);
}
}
}, 1000);
}
});
}
}
the output doesn't change only showing one index and doesn't change to the next index
edit:
it does work but on the output, it only shows the last index but still doesn't change
edit 2:
Okay so I fixed it with new code and try some of you guys help
this is new code
package com.example.testtingskripsi;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Arrays;
import java.util.List;
import java.util.Collections;
public class MainActivity extends AppCompatActivity {
public String [] ArrayA ={"80","81","82","83","84","85"};
public TextView mViewLabel;
boolean continueThread=true;
int count =0;
Thread t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewLabel = (TextView) findViewById(R.id.textChanger);
List<String> list = Arrays.asList(ArrayA);
Collections.shuffle(list);
t = new Thread(){
#Override
public void run() {
while(continueThread){
try{
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
if(count<=6){
count++;
}else{
count--;
}
mViewLabel.setText(list.get(count));
}
});
}catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
}
public void BtnStart(View view){
t.start();;
}
public void BtnStop(View view){
continueThread=false;
}
}
it stop at end of array, so i want it to doing the loop until i pressed stop button any help

Already figured it out so okay thank you all for helling me

You probably need to add some delay inside the for loop.
Try Thread.sleep inside the loop.
The device changes 60 fps so its hard to view the changes for a small loop

Related

I cant display the image on the screen. Android Studio

I wanted to make a program that would output a image fron the internet by a link to the screen, but the image either appears as a cropped strip, or does not appear at all. I will be very grateful for you help
code
package com.example.myapplication2;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private EditText s;
private TextView d;
private Button button1;
private URL link;
private InputStream j;
private Bitmap bitmap;
private ImageView image4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
d = findViewById(R.id.textView12);
s = findViewById(R.id.editText1);
button1 = findViewById(R.id.button1);
image4 = findViewById(R.id.imageView3);
}
#Override
protected void onResume() {
super.onResume();
}
public void onClickStart(View view){
new Thread(new Runnable() {
#Override
public void run() {
try {
link = new URL(s.getText().toString());
try {
j = (InputStream)link.getContent();
}
catch (IOException e){
d.setText("fail");
}
}
catch (MalformedURLException e){
d.setText("fail");
}
runOnUiThread(new Runnable() {
#Override
public void run() {
bitmap = BitmapFactory.decodeStream(j);
image4.setImageBitmap(bitmap);
}
});
}
}).start();
}
}
enter image description here
enter image description here
It is possible in incorrect handling of the permission or file type, I would appreciate your help

Is using a variable as parameter(delaymillis) in Android postDelayed available?

I want to move to another Activity after 5 seconds.
(Step4Activity -> WeightActivity)
I found this code, and it worked.
new Handler().postDelayed(new Runnable()
{
#Override
public void run()
{
Intent intent = new Intent(Step4Activity.this, WeightActivity.class);
startActivity(intent);
}
}, 5000);
But I want to use a variable 'count' as a parameter 'delaymillis' like this, but it didn't work.
new Handler().postDelayed(new Runnable()
{
#Override
public void run()
{
Intent intent = new Intent(Step4Activity.this, WeightActivity.class);
startActivity(intent);
}
}, count * 1000); // int count = 5
Is there any way to use variable?
Here's my full code. (Step4Activity.java)
package com.example.starbucksook;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Timer;
import java.util.TimerTask;
public class Step4Activity extends AppCompatActivity {
//TextView countdown_text;
//LinearLayout timeCountSettingLV, timeCountLV;
//TextView hourET, minuteET, secondET;
//TextView hourTV, minuteTV, secondTV, finishTV;
//Button startBtn;
//int hour, minute, second;
int count = 5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_step4);
// Unrelated code skipped
/*Here is 'Handler-postDelayed' method.*/
new Handler().postDelayed(new Runnable()
{
#Override
public void run()
{
Intent intent = new Intent(Step4Activity.this, WeightActivity.class);
startActivity(intent);
}
}, count * 1000);
}

My code keep crashing with the same error (Cannot find symbol variable!)

package com.example.q;
import androidx.appcompat.app.AppCompatActivity;
import android.app.WallpaperManager;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends AppCompatActivity {
int images[] = new int[] { R.drawable.i1, R.drawable.i2, R.drawable.i3, }
Button btn;
int i=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
new Timer().schedule(new ChangeWallpaper(),0, 30000);
}
});
}
class ChangeWallpaper extends TimerTask{
#Override public void run() {
WallpaperManager wallpaperManager = WallpaperManager.getInstance(getBaseContext());
try {
wallpaperManager.setBitmap( BitmapFactory.decodeResource(getResources(),images[i]));
i++;
if(i==3){
i=0;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I'm having this error as mentioned in the title, originally i was facing the "R" package problem, but now it is this perhaps it could be connected ? I've already tried uninstalling and reinstalling it doesn't seem to work any suggestions ?
Cannot find symbol variable i1:17 Cannot find symbol variable i2:18
Cannot find symbol variable i3:19
public class MainActivity extends AppCompatActivity {
int images[] = new int[]{R.drawable.i1,R.drawable.i2, R.drawable.i3};
You just need to remove the COMMA in the end of the last item in the array.
But the question is too broad without a proper code to verify if the only answer would be this.

how to check radio buttons programatically when the scanned qr match with text in the listview

I am developing attendance system and i have a listview with students name i want to programatically check or uncheck the radio buttons in the listview when the scanned qr matchs the student name I tried to do it in the ontextchengeListner method of txtresult but the text is changing many time even in reading a single qr
This are my java classes
CustomAdapter.java
package com.attendance.olana.qr_scanner;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by olana on 23/03/2018.
*/
public class CustomAdapter extends BaseAdapter {
Context context;
String[] questionsList;
public static String message;
LayoutInflater inflter;
public static TextView question ;
public static RadioButton yes,no ;
public static ArrayList<String> selectedAnswers;
public CustomAdapter(Context applicationContext, String[] questionsList) {
this.context = context;
this.questionsList = questionsList;
// initialize arraylist and add static string for all the questions
selectedAnswers = new ArrayList<>();
for (int i = 0; i < questionsList.length; i++) {
selectedAnswers.add("Not Attempted");
}
inflter = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
return questionsList.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.main, null);
// get the reference of TextView and Button's
question = (TextView) view.findViewById(R.id.question);
yes = (RadioButton) view.findViewById(R.id.yes);
no = (RadioButton) view.findViewById(R.id.no);
// perform setOnCheckedChangeListener event on yes button
yes.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// set Yes values in ArrayList if RadioButton is checked
if (isChecked)
selectedAnswers.set(i, "Present");
}
});
// perform setOnCheckedChangeListener event on no button
no.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// set No values in ArrayList if RadioButton is checked
if (isChecked)
selectedAnswers.set(i, "Absent");
}
});
// set the value in TextView
question.setText(questionsList[i]);
return view;
}
}
list.java
package com.attendance.olana.qr_scanner;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.Toast;
/**
* Created by olana on 23/03/2018.
*/
public class list extends AppCompatActivity {
ListView simpleList;
public static String[] questions;
Button submit,scan;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
scan =(Button)findViewById(R.id.scan);
// get the string array from string.xml file
questions = getResources().getStringArray(R.array.student);
// get the reference of ListView and Button
simpleList = (ListView) findViewById(R.id.simpleListView);
submit = (Button) findViewById(R.id.submit);
// set the adapter to fill the data in the ListView
CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), questions);
simpleList.setAdapter(customAdapter);
scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i;
i = new Intent(list.this,MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
}
});
// perform setOnClickListerner event on Button
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String message = "";
// get the value of selected answers from custom adapter
for (int i = 0; i < CustomAdapter.selectedAnswers.size(); i++) {
message = message + "\n" + (i + 1) + " " + CustomAdapter.selectedAnswers.get(i);
}
// display the message on screen with the help of Toast.
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
});
}
}
MainActivity.java
package com.attendance.olana.qr_scanner;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Vibrator;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.SparseArray;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.barcode.Barcode;
import com.google.android.gms.vision.barcode.BarcodeDetector;
import java.io.IOException;
import java.util.jar.Manifest;
public class MainActivity extends AppCompatActivity {
BarcodeDetector barcodeDetector;
SurfaceView camerapreview;
CameraSource cameraSource;
TextView txtresult;
String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button finish = (Button) findViewById(R.id.finish);
//Button scan = (Button) findViewById(R.id.scan);
finish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
});
camerapreview = (SurfaceView) findViewById(R.id.camerapreview);
txtresult = (TextView) findViewById(R.id.txtresult);
barcodeDetector = new BarcodeDetector.Builder(this)
.setBarcodeFormats(Barcode.QR_CODE)
.build();
cameraSource = new CameraSource
.Builder(this, barcodeDetector)
.setRequestedPreviewSize(640, 480)
.build();
//add event
camerapreview.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
cameraSource.start(camerapreview.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
try {
cameraSource.start(camerapreview.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> qrcodes = detections.getDetectedItems();
if (qrcodes.size() != 0) {
txtresult.post(new Runnable() {
#Override
public void run() {
//create vibration
Vibrator vibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(100);
txtresult.setText(qrcodes.valueAt(0).displayValue);
//barcodeDetector.release();
}
});
}
}
});
}
}
Please tell me where i can implement these the programatically checking or unchecking the radio button when the name in the listview matchs the scanned qr please help me

How do i connect my main thread with a created worker thread?

Hey I have a trouble with using a room database on android studio java.
I am trying to save the components of a class when I click on a save button.
but the thing is that it is a bad thing to use a save or download call on a main thread so I am creating my own thread but how do I then outside of that thread use the data? my class that I'm doing this in looks like this...
UPDATE: Should this work then?
package com.example.jenso.paperseller;
import android.arch.persistence.room.Room;
import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class CreateCustomer extends AppCompatActivity {
EditText name;
EditText address;
EditText phonenumber;
EditText email;
Button saveCustomer;
PapperSellerDatabase pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_customer);
name = findViewById(R.id.nameInput);
address = findViewById(R.id.addressInput);
phonenumber = findViewById(R.id.phonenumberInput);
email = findViewById(R.id.emailInput);
saveCustomer = findViewById(R.id.saveInput);
setTheDataBase();
saveCustomer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(CreateCustomer.this, MainActivity.class));
pd.customerDao().insertAll(new Customer(name.getText().toString(),address.getText().toString(),phonenumber.getText().toString(),email.getText().toString()));
}
});
}
public void setTheDataBase(){
new Thread(new Runnable() {
#Override
public void run() {
//here you obtain data from async source
PapperSellerDatabase pd = Room.databaseBuilder(getApplicationContext(),PapperSellerDatabase.class,"production")
.fallbackToDestructiveMigration()
.build();
}
}).start();
}
}
and on the load side I do this?
package com.example.jenso.paperseller;
import android.arch.persistence.room.Room;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.ThemedSpinnerAdapter;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
List<Customer> customers;
PapperSellerDatabase database;
FloatingActionButton fab;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerView = findViewById(R.id.recycler);
customers = new ArrayList<>();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new PapperRecyclerAdapter(customers,this);
recyclerView.setAdapter(adapter);
downloadTheData();
fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: Do this when you click");
startActivity(new Intent(MainActivity.this, CreateCustomer.class));
}
});
}
private void downloadTheData(){
new Thread(new Runnable() {
#Override
public void run() {
//here you obtain data from async source
PapperSellerDatabase pd = Room.databaseBuilder(getApplicationContext(),PapperSellerDatabase.class,"production")
.fallbackToDestructiveMigration()
.build();
customers = pd.customerDao().getAllCustomers();
}
}).start();
}
}
so how would I go further with if I click the button I wanna save the data to the room database and then leave the view?
Whenever you work with premises, as in JavaScript for instance, you are not sure when the premise will be fulfilled, or in other words, when your date will become available. So what is usually done is to declare the variable in higher scope, which will make it available both to the thread that should set it (worker) and to the one should use it (main).
Update
public class Example {
//here you initialize your variable that will contain data
List <RemoteData> remoteData = null;
....
public void hereRemoteDataIsUsed(){
if(remoteData != null){
//use remoteData here
...
}
}
....
public void hereRemoteDataIsSet(){
new Thread(new Runnable() {
#Override
public void run() {
//here you obtain data from async source
remoteData = getDataFromSomeAsyncSource();
}
}).start();
}
}
You can notice that in the method where the data is obtained nothing is returned. Since it is an asynchronous operation you don't know when it will be fulfilled. You just know that it will be, eventually. So you just wait until it is available (remoteData != null).

Categories

Resources