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();
Related
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.
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.
I am currently experimenting with layouts and opening new pages, I would like to open one page with a OnLongClickListener but a toast with a OnClickListener using the same text view box.
This is what I've designed so far. It won't work as the long click needs to output a boolean. Any Ideas?
XML main
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android.how_to_use.MainActivity"
android:id="#+id/main_view">
<TextView
android:id="#+id/long_press_textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Long Press To Open \n'Drag n Drop'"/>
</LinearLayout>
XML 2nd page
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<ImageView
android:id="#+id/swirl_img"
android:src="#drawable/Swirl"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
MainActivity.Java
public class MainActivity extends AppCompatActivity {
private LinearLayout mainView;
private TextView txtView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtView = (TextView) findViewById(R.id.long_press_textView);
addListenerLongPressBtn();
addListenerOnClickBtn();
}
public void addListenerOnClickBtn() {
txtView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "Press Secret Button for Longer", Toast.LENGTH_SHORT).show();
}
});
}
public void addListenerLongPressBtn() {
txtView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
Intent intent = new Intent(this, DragDropActivity.class);
startActivity(intent);
return true;
}
});
}
}
I found a solution to my own problem.
public void addListenerLongPressBtn() {
txtView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
Intent intent = new Intent(view.getContext(), DragDropActivity.class);
startActivity(intent);
return true;
}
});
}
I am using SeekBar to change the opacity level in drawing But I am getting Nullpointer exception in the lines
seekOpq.setMax(100);
and
seekTxt.setText(currLevel);
in the following code..
public void onClick(View view){
if(view.getId()==R.id.opacity_btn){
//launch opacity chooser
final Dialog seekDialog = new Dialog(this);
final TextView seekTxt = (TextView)seekDialog.findViewById(R.id.opq_txt);
final SeekBar seekOpq = (SeekBar)seekDialog.findViewById(R.id.seek);
Toast.makeText(getApplicationContext(),
"start.", Toast.LENGTH_SHORT).show();
seekDialog.setTitle("Opacity level:");
seekDialog.setContentView(R.layout.opacity_chooser);
seekOpq.setMax(100);
int currLevel = drawView.getPaintAlpha();
seekTxt.setText(currLevel);
seekOpq.setProgress(currLevel);
seekOpq.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
seekTxt.setText(Integer.toString(progress)+" % ");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar){}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {}
});
Button opqBtn = (Button)seekDialog.findViewById(R.id.opq_ok);
opqBtn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
drawView.setPaintAlpha(seekOpq.getProgress());
Toast.makeText(getApplicationContext(),
"end.", Toast.LENGTH_SHORT).show();
seekDialog.dismiss();
}
});
}
I have tried giving numeric arguments manualy to these lines like
seekTxt.setText(50);
But the error still remains the same
This is my opacity_chooser.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:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/opq_txt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:gravity="center"
android:text="100%"
android:textStyle="bold" />
<SeekBar
android:id="#+id/seek"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp" />
<Button
android:id="#+id/opq_ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OK" />
</LinearLayout>
First set Content View after initialize seekbar & textview.
eg.
final Dialog seekDialog = new Dialog(this);
seekDialog.setContentView(R.layout.opacity_chooser);
final TextView seekTxt = (TextView)seekDialog.findViewById(R.id.opq_txt);
final SeekBar seekOpq = (SeekBar)seekDialog.findViewById(R.id.seek);
Toast.makeText(getApplicationContext(),
"start.", Toast.LENGTH_SHORT).show();
seekDialog.setTitle("Opacity level:");
seekOpq.setMax(100);
-------------------
I am currently developing an android application in which purpose is to play a large variety of every-day sounds on click.
I have 3 activities : home, animaux and transports.
Home is fine, animaux is fine (it plays all the sounds without any problems).
But I want to integrate admob on Transports acivity. Ads display well, but when I cluck on the sounds buttons, nothing happens. If you could help me understand my mistake and how to fix it, it would be very nice !
Here is transports.java
public class Transports extends Activity {
private AdView adView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transports);
// Create the adView
adView = new AdView(this, AdSize.BANNER, "xxxxxx"
// Lookup your LinearLayout assuming it's been given
// the attribute android:id="#+id/mainLayout"
LinearLayout layout = (LinearLayout)findViewById(R.id.linearLayout1);
// Add the adView to it
layout.addView(adView);
// Initiate a generic request to load it with an ad
adView.loadAd(new AdRequest());
}
#Override
public void onDestroy() {
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
private MediaPlayer mPlayer = null;
/** Called when the activity is first created. */
public void onCreate1(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transports);
Button btn_sound_sncf2 = (Button) findViewById(R.id.sncfnew);
btn_sound_sncf2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
playSound(R.raw.sncf2);
}
});
Button btn_sound_sncf1 = (Button) findViewById(R.id.sncf1);
btn_sound_sncf1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
playSound(R.raw.sncf1);
}
});
}
#Override
public void onPause() {
super.onPause();
if(mPlayer != null) {
mPlayer.stop();
mPlayer.release();
}
}
private void playSound(int resId) {
if(mPlayer != null) {
mPlayer.stop();
mPlayer.release();
}
mPlayer = MediaPlayer.create(this, resId);
mPlayer.start();
}
}
And here is the transports.xml code :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="fill_vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".Transports" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:gravity="left"
android:orientation="vertical" >
<com.google.ads.AdView
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ads:adSize="BANNER"
ads:adUnitId="xxxxx"
ads:loadAdOnCreate="true"
ads:testDevices="TEST_EMULATOR, TEST_DEVICE_ID"
android:gravity="top" >
</com.google.ads.AdView>
<Button android:id="#+id/sncfnew"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/sncf1"
android:layout_below="#+id/sncf1"
android:layout_marginTop="38dp"
android:text="#string/sncfnew" />
<Button android:id="#+id/sncf1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/linearLayout1"
android:layout_below="#+id/linearLayout1"
android:text="#string/sncf1" />
</LinearLayout>
</RelativeLayout>
I wonder if the problem isn't in my xml file : I have a lot of difficulties to maker a clear interface with the linearlayout required by admob.
You aren't actually setting the listeners. You have that code in a method:
public void onCreate1(Bundle savedInstanceState) {
that is never called. Move that code to the actual onCreate() method and it should work fine.