This question already has answers here:
android.content.res.Resources$NotFoundException: String resource ID #0x0
(8 answers)
Closed 3 years ago.
I want to display a timer from 1 to 100 in my TextView, but this throws me an Exception. My application throws a RuntimeException like shown below:
Thanks in advance for your help.
java.lang.RuntimeException: An error occurred while executing
doInBackground()
My MainActivity class where the RuntimeException is thrown.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView txt = findViewById(R.id.txt);
Button button1 = findViewById(R.id.bt1);
Button button2 = findViewById(R.id.bt2);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new QQ().execute();
}
});
}
public void onProgressUpdate(int i) {
TextView txt = findViewById(R.id.txt);
Button button1 = findViewById(R.id.bt1);
Button button2 = findViewById(R.id.bt2);
txt.setText(i);
}
private class QQ extends AsyncTask<Integer, Integer, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Integer doInBackground(Integer... args) {
for (int i = 0; i < 1000000; i++) {
try {
Thread.sleep(1000); ///задержка
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress(i);
return null;
}
return null;
}
private void publishProgress(int i) {
publishProgressq(i);
}
protected void onPostExecute(int i) {
}
}
private void publishProgressq(int i) {
onProgressUpdate(i);
}
}
My Layout class in xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#bbbbbb"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#bbbbbb"
android:gravity="top"
android:orientation="horizontal">
<TextView
android:id="#+id/txt"
android:layout_width="151dp"
android:layout_height="110dp"
android:textSize="45dp"
android:text="0">
</TextView>
<Button
android:id="#+id/bt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="START" />
<Button
android:id="#+id/bt2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="STOP" />
</LinearLayout>
</LinearLayout>
You can change your code as below:
public void onProgressUpdate(int i) {
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView txt = findViewById(R.id.txt);
Button button1 = findViewById(R.id.bt1);
Button button2 = findViewById(R.id.bt2);
txt.setText(i);
}
});
}
It will run on main thread.
Inside your public void onProgressUpdate , set text like this :
txt.setText(String.valueOf(i));
If you set a TextView to an int, it will be interpreted as an Android resource id. If you want the value of the int as your text (and not the resource it points to), make it a String first.
Related
I have a problem on getting my imageview button to work onclick. what im trying to do is to make the first image invisible so that the second one behind it can appear and at the same time define int special based on what image that has been clicked.
public class TrainingActivity extends AppCompatActivity implements View.OnClickListener {
public static int special;
public static ImageView a12,b13,a12a,b13a;
#Override
protected void onCreate(Bundle savedInstanceState) {
////////////////////////////////////////////////////////////////////////
super.onCreate(savedInstanceState);
setContentView(R.layout.home_page);
a12 = (ImageView) findViewById(R.id.young);
b13 = (ImageView) findViewById(R.id.old);
a12a = (ImageView) findViewById(R.id.young2);
b13a = (ImageView) findViewById(R.id.old2);
a12.setOnClickListener(this);
b13.setOnClickListener(this);
a12a.setOnClickListener(this);
b13a.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.young) {
a12.setVisibility(View.GONE);
a12a.setVisibility(View.VISIBLE);
special =0;
} else {
a12.setVisibility(View.VISIBLE);
a12a.setVisibility(View.GONE);
}
if (v.getId() == R.id.old) {
b13.setVisibility(View.GONE);
b13a.setVisibility(View.VISIBLE);
special =1;
} else {
b13.setVisibility(View.VISIBLE);
b13a.setVisibility(View.GONE);
}
}
this is my main class file. I've had already tried this codes in a new project and it works there but somehow doesn't here.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:background="#color/gray_color"
tools:context="com.codestudioapps.cardioexcercise.WalkandStep.activities.TrainingActivity">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:id="#+id/young2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="35dp"
android:layout_gravity="center_horizontal|left|center_vertical"
android:src="#drawable/img_body_surface_area1"
/>
<ImageButton
android:id="#+id/young"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="35dp"
android:layout_gravity="center_horizontal|left|center_vertical"
android:src="#drawable/img_body_surface_area" />
<ImageButton
android:id="#+id/old2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="35dp"
android:layout_gravity="center_horizontal|right|center_vertical"
android:src="#drawable/img_body_fat1"
/>
<ImageButton
android:id="#+id/old"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="35dp"
android:layout_gravity="center_horizontal|right|center_vertical"
android:src="#drawable/img_body_fat" />
</FrameLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
And this is the layout. The problem might happen because of my manifest file but im unsure. Does anyone have any ideas?
Your code seems okay. Just, casting problem i.e. ImageButton to ImageView.
Your code should be as follows:
public class DemoActivity extends AppCompatActivity implements View.OnClickListener {
public static int special;
public static ImageButton a12, b13, a12a, b13a;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo);
a12 = findViewById(R.id.young);
b13 = findViewById(R.id.old);
a12a = findViewById(R.id.young2);
b13a = findViewById(R.id.old2);
a12.setOnClickListener(this);
b13.setOnClickListener(this);
a12a.setOnClickListener(this);
b13a.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.young) {
a12.setVisibility(View.GONE);
a12a.setVisibility(View.VISIBLE);
special = 0;
} else {
a12.setVisibility(View.VISIBLE);
a12a.setVisibility(View.GONE);
}
if (v.getId() == R.id.old) {
b13.setVisibility(View.GONE);
b13a.setVisibility(View.VISIBLE);
special = 1;
} else {
b13.setVisibility(View.VISIBLE);
b13a.setVisibility(View.GONE);
}
}
}
sorry for annoying you but i am in my first step in android programming and need your support
the question is,
i want to change between photos using next and previous Button
i have 3 photos in an array
and 2 button (next and previous )
put when i started my app. i should press next button twice to change the photo
also in previous i should press it twice to change back
hope someone help me to improve the code down
public class SabahList extends AppCompatActivity {
ImageView img;
int[] mario = new int[]{R.drawable.image_a,R.drawable.image_b,R.drawable.image_c};
int n =0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sabah_list);
img= (ImageView)findViewById(R.id.imageView2);
}
public void btu_next(View view) {
img.setImageResource(mario[n]);
if(n<2)
n++;
}
public void btu_prev(View view) {
img.setImageResource(mario[n]);
if(n>0)
n--;
}
}
Here is your logic problem. Your button's function command them set resource first, then increase/decease value, therefore when you click the second time, it will be set as previous increasingly/decreasingly.
public void btu_next(View view) {
if(n < 2)
n++;
img.setImageResource(mario[n]);
}
This answer may helpful to you if you are using normal array added images from drawable
//Your xml like this
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.devobal.quitchet.SabahList"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/previous"
android:text="previous"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/next"
android:text="next"/>
</LinearLayout>
<ImageView
android:id="#+id/imageView2"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
//And your Activity like this
public class SabahList extends AppCompatActivity {
ImageView imageView2;
Button previous,next;
int i=0;
private int[] textureArrayWin = {R.drawable.star1,R.drawable.star2, R.drawable.star3,};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sabah_list);
imageView2 = (ImageView)findViewById(R.id.imageView2);
previous = (Button)findViewById(R.id.previous);
next = (Button)findViewById(R.id.next);
if(i==0){
previous.setVisibility(View.GONE);
}
if (i==2){
next.setVisibility(View.GONE);
}
previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
imageView2.setImageResource(textureArrayWin[i]);
i--;
if(i==0){
previous.setVisibility(View.GONE);} else{ previous.setVisibility(View.VISIBLE);}
if (i==2){
next.setVisibility(View.GONE);
} else{next.setVisibility(View.VISIBLE)}
}
});
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//if you are loading from bitmap
imageView2.setImageResource(textureArrayWin[i]);
i++;
if(i==0){
previous.setVisibility(View.GONE); } else {previous.setVisibility(View.VISIBLE); }
if (i==2){
next.setVisibility(View.GONE);
} else{next.setVisibility(View.VISIBLE)}
}
});
}
}
This is my first question. I want to add a textview to an existing layout every second using the addView method. And I want to print the text down while they remain. But nothing appear in the layout. Hope somebody can help me.
This is my code.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = this.findViewById(R.id.btn);
textView = this.findViewById(R.id.tv1);
linearLayout = this.findViewById(R.id.line1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
runThread();
}
});
}
private void runThread(){
new Thread() {
#Override
public void run() {
while(i++ < 10) {
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView createdTextView = new TextView(MainActivity.this);
createdTextView.setText(new Date(System.currentTimeMillis()).toString() + i);
linearLayout.addView(createdTextView);
}
});
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}.start();
}
This is avtivity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/line1"
tools:context="com.example.runonuithread.MainActivity">
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button"/>
<TextView
android:id="#+id/tv1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Try this:
LayoutParams lparams = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView createdTextView = new TextView(MainActivity.this);
createdTextView.setText(new Date(System.currentTimeMillis()).toString() + i);
createdTextView.setLayoutParams(lparams);
linearLayout.addView(createdTextView);
I'm new to Android development so please bear with me.
I have the code inside an activity that implements qr scanning. Basically there is an activity before this segments of codes, but its just clicking of a button to go here. and whenever I do that, my app crashes and that is the error that returns. The idea of the app is once the user click the button, it will first display a qr scanner, once it has been scanned, it will now call this XML File
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_scan"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="#drawable/scanbg"
tools:context=".ScanActivity">
<RelativeLayout
android:layout_width="300dp"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginLeft="25dp"
android:layout_marginRight="25dp"
android:layout_marginTop="62dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Question Here"
android:textSize="22dp"
android:id="#+id/questionhere"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/questionhere"
android:hint="Answer"
android:id="#+id/answerhere"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Correct or not indicator"
android:id="#+id/indicator"
android:layout_below="#id/answerhere"
android:textSize="18dp"/>
<!--this textview will be programmed to be changed as correct or not-->
<!--if answer == correct then "correct!" else "wrong answer"-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Point(s):"
android:id="#+id/userpoints"
android:layout_below="#id/indicator"
android:textSize="18dp"/>
<Button
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/userpoints"
android:layout_alignParentEnd="true"
android:text="Go"
android:textSize="14dp"
android:background="#B0DAD5"
android:id="#+id/gosagot"/>
</RelativeLayout>
and Here is the java file
public class ScanActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler{
Button validateanswer;
ProgressDialog progress;
private ZXingScannerView mScannerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan);
mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
mScannerView.setResultHandler(this);
mScannerView.startCamera();
validateanswer = (Button)findViewById(R.id.gosagot); //Im having error here
validateanswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
progress.setMessage("Connecting...");
progress.setCancelable(false);
progress.show();
EditText theanswer = (EditText)findViewById(R.id.answerhere);
String sagotdito = theanswer.getText().toString();
RequestFactory.confirmanswer(ScanActivity.this, sagotdito, new RequestCallback<Boolean>() {
#Override
public void onSuccess(Boolean response) {
runOnUiThread(new Runnable() {
#Override
public void run() {
finish();
//load new question
progress.dismiss();
}
});
}
#Override
public void onFailed(String message) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(ScanActivity.this, "Wrong Answer. Try Again!", Toast.LENGTH_LONG).show();
progress.dismiss();
}
});
}
});
}
});
}
continuation...
#Override
protected void onPause() {
super.onPause();
mScannerView.stopCamera();
}
#Override
public void handleResult(final Result result) {
Log.w("handleResult",result.getText());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final EditText answertoQuestion = new EditText(this);
answertoQuestion.setHint("answer");
builder.setTitle("Scan Result");
builder.setMessage(result.getText());
builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
setContentView(R.layout.activity_scan);
TextView j = (TextView)findViewById(R.id.questionhere);
EditText k = (EditText)findViewById(R.id.answerhere);
String n = k.getText().toString();
j.setText(result.getText());
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
please help me.
If you check the examples of ZXing...
In your activity XML, you can add a region for the QR scanner.
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Grab that and add the scanner view there.
public class ScannerActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private ZXingScannerView mScannerView;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
setContentView(R.layout.activity_simple_scanner);
ViewGroup contentFrame = (ViewGroup) findViewById(R.id.content_frame);
mScannerView = new ZXingScannerView(this);
contentFrame.addView(mScannerView);
}
Your error is that you can't findViewById on your button when you replaced the content view with some other view that doesn't have the ID you want to find.
And even if you "switched" findViewById and setContentView around, your code wouldn't crash, but you would no longer have a button in the content view, so having the click action would be pointless.
The problem is that the button is a part of activity_scan and you set setContentView(mScannerView) to other layout.You are bound to get this error as the activity does not have a refernce to the view(button) you are refering.
What you can do is make the mScannerView a part of your main layout and then get it with findViewById();
How to update my UI button for disabled button on/off if i have condition. The condition : if i get value = 1.0 the button power on is disabled & and if i get value 0 the button power off disabled. I want the button always show up the new value.
This is my code :
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_controller, container, false);
mSwitchStatus = (TextView) rootView.findViewById(R.id.statusSwitch);
ImageButton On = (ImageButton)rootView.findViewById(R.id.on);
ImageButton Off = (ImageButton)rootView.findViewById(R.id.off);
callAsynchronousTask();
On.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(getActivity().getApplication(), "ON", Toast.LENGTH_SHORT).show();
SendApi sendApi = new SendApi();
sendApi.execute();
}
});
Off.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Toast.makeText(getActivity().getApplication(), "OFF", Toast.LENGTH_SHORT).show();
SendApi sendApi = new SendApi();
sendApi.execute();
}
});
// Inflate the layout for this fragment
return rootView;
}
Repeat AsyncTask
public void callAsynchronousTask() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
GetApi getApi = new GetApi();
getApi.execute();
} catch (Exception e) {
android.util.Log.i("Error", "Error");
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 100);
}
AsyncTask for GETApi
public class GetApi extends AsyncTask<Object, Object, Value[]> {
private final String API_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
private final String SWITCHID = "xxxxxxxxxxxxxxxxxxxxxxxxx";
private ImageButton On,Off ;
#Override
protected Value[] doInBackground(Object... params) {
ApiClient apiClient = new ApiClient(API_KEY);
Variable statusSwitch = apiClient.getVariable(SWITCHID);
Value[] variableValues = statusSwitch.getValues();
return variableValues;
}
#Override
protected void onPostExecute(Value[] variableValues) {
String status = Double.toString(variableValues[0].getValue());
mSwitchStatus.setText(status);
if(status.equals("1.0")){
On.setVisibility(View.INVISIBLE);
}
}
}
Fragment_controller.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#1d4851"
tools:context=".activity.ControllerFragment">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/off"
android:src="#drawable/ic_off"
android:background="#null"
android:layout_marginTop="79dp"
android:layout_below="#+id/textView2"
android:layout_alignLeft="#+id/on"
android:layout_alignStart="#+id/on"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/on"
android:background="#null"
android:src="#drawable/ic_on"
android:layout_marginTop="87dp"
android:layout_alignTop="#+id/off"
android:layout_centerHorizontal="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Water Pump Controller "
android:id="#+id/textView2"
android:textColor="#ffffff"
android:textSize="20dp"
android:layout_marginTop="19dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" "
android:id="#+id/statusSwitch"
android:textColor="#ffffff"
android:textSize="20dp"
android:layout_marginTop="250dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
you have initialize your button in onCreateView like
ImageButton On = (ImageButton)rootView.findViewById(R.id.on);
and trying to access it in onPostExecute().they aren't global.
And to disable you have to call setEnable(false) not setVisibility
And you can also send it as Rathna Kumaran said.
public class GetApi extends AsyncTask<Object, Object, Value[]> {
private Button button;
public GetApi(Button mButton){
this.button = button;
}
private final String API_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
private final String SWITCHID = "xxxxxxxxxxxxxxxxxxxxxxxxx";
#Override
protected Value[] doInBackground(Object... params) {
ApiClient apiClient = new ApiClient(API_KEY);
Variable statusSwitch = apiClient.getVariable(SWITCHID);
Value[] variableValues = statusSwitch.getValues();
return variableValues;
}
#Override
protected void onPostExecute(Value[] variableValues) {
String status = Double.toString(variableValues[0].getValue());
mSwitchStatus.setText(status);
if(status.equals("1.0")){
button.setVisibility(View.INVISIBLE);
}
}
}
1.Create a constructor in a AsyncTask and send the button as parameter. ex. getApi(buttonOne).execute();
Inside a getApi() constructor declare a local variable "Button" and assigned to that.
In onPostExecute() -> buttonOne.setVisibility(View.INVISIBLE).
In asyncTask , "onPostExecute()" will perform in a main thread. UI elements should only get update in a main thread. So that passing a UI element into an Asynctask and it can be update inside the onPostExecute.