Android Studio can't find Resuorces - java

This is the error message which shows up when I run the apk on my virtual device.
05-03 13:00:03.652 2354-2354/de.hochrad.hochradapp I/art﹕ Not late-enabling -Xcheck:jni (already on)
05-03 13:00:05.966 2354-2354/de.hochrad.hochradapp D/AndroidRuntime﹕ Shutting down VM
05-03 13:00:05.970 2354-2354/de.hochrad.hochradapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: de.hochrad.hochradapp, PID: 2354
java.lang.RuntimeException: Unable to start activity ComponentInfo{de.hochrad.hochradapp/de.hochrad.hochradapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.widget.Toast.<init>(Toast.java:101)
at android.widget.Toast.makeText(Toast.java:250)
at de.hochrad.hochradapp.MainActivity.onCreate(MainActivity.java:26)
at android.app.Activity.performCreate(Activity.java:5937)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
        at android.app.ActivityThread.access$800(ActivityThread.java:144)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
05-03 13:00:08.238 2354-2354/de.hochrad.hochradapp I/Process﹕ Sending signal. PID: 2354 SIG: 9
Somehow it cannot find the required Resources.
I hope you can help me!!!
Thx for all answers!!!
package de.hochrad.hochradapp;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
ArrayAdapter<String> klassen_adapter;
Vertretungsplan vertretungsplan;
Spinner klassen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(null, "Laden...", Toast.LENGTH_SHORT).show();
klassen_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
klassen = (Spinner) findViewById(R.id.klassenspinner);
Thread downloadThread = new Thread() {
public void run() {
vertretungsplan = new Vertretungsplan("1");
runOnUiThread(new Runnable() {
#Override
public void run() {
if (vertretungsplan.Ex != null) {
klassen_adapter.add("Fehler!");
} else {
klassen_adapter.add("Wähle deine Klasse!");
for (Klassenvertretung s : vertretungsplan.Klassen) {
klassen_adapter.add(s.Bezeichnung);
}
}
}
});
}
};
downloadThread.start();
klassen.setAdapter(klassen_adapter);
klassen.setSelection(0);
klassen.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(parent.getContext(),
"Deine Auswahl ist:" + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
package de.hochrad.hochradapp;
import java.util.ArrayList;
import java.util.List;
public class Klassenvertretung {
public String Bezeichnung;
public List<Vertretung> Vertretungen = new ArrayList<Vertretung>();
public void Hinzufügen(Vertretung neuesElement) {
Vertretungen.add(neuesElement);
}
}
package de.hochrad.hochradapp;
public class Vertretung {
public String Klasse;
public String Stunde;
public String Art;
public String Fach;
public String Raum;
public String stattFach;
public String stattRaum;
public String Informationen;
}
package de.hochrad.hochradapp;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Vertretungsplan {
public Vertretungsplan(String woche) {
Woche = woche;
Einlesen(woche);
}
public String Woche;
public Exception Ex;
public List<Klassenvertretung> Klassen = new ArrayList<Klassenvertretung>();
private void Hinzufügen(Klassenvertretung neuesElement) {
Klassen.add(neuesElement);
}
private void Einlesen(String woche) {
try {
for (int webseite = 1; webseite < 10000; webseite++) {
Klassenvertretung klassenvertretung = new Klassenvertretung();
String teilseite = "0000";
if (webseite < 10)
teilseite = teilseite + "0";
teilseite = teilseite + webseite;
Connection connection = Jsoup
.connect("www.gymnasium-hochrad.de/Vertretungsplan/Vertretungsplan_Internet/"
+ woche + "/w/w" + teilseite + ".htm");
Document doc = connection.get();
Element h2 = doc.select("h2").get(0);
klassenvertretung.Bezeichnung = h2.text();
Element table = doc.select("table").get(1);
Element[] elemente = table.select("tr").toArray(new Element[0]);
for (int i = 1; i < elemente.length; i++) {
Element[] tds = elemente[i].select("td").toArray(
new Element[0]);
Vertretung vertretung = new Vertretung();
vertretung.Klasse = tds[0].text();
vertretung.Stunde = tds[1].text();
vertretung.Art = tds[2].text();
vertretung.Fach = tds[3].text();
vertretung.Raum = tds[4].text();
vertretung.stattFach = tds[5].text();
vertretung.stattRaum = tds[6].text();
vertretung.Informationen = tds[7].text();
klassenvertretung.Hinzufügen(vertretung);
}
Hinzufügen(klassenvertretung);
}
} catch (IOException io) {
if (Klassen.size() == 0) {
Ex = io;
}
} finally {
}
}
}
okay here is my code. I am form germany and so lots of Names are german (i hope thats not a problem.
Maybe it helps.
I guess the error must be in the main activity in one of the toasts. But dont hesitate to look at the other lines.

A/c to logcat error your are getting null reference error. try to update this line
Toast.makeText(parent.getContext(),
"Deine Auswahl ist:" + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();
with the following code
Toast.makeText(MainActivity.this,
"Deine Auswahl ist:" + parent.getItemAtPosition(position).toString(), Toast.LENGTH_SHORT).show();

You have not initialised your adapter namely "klassen_adapter" in your main activity. It's null and invoking any method on it will be null pointer exception

Related

TextWatcher shuts down my application after starting up

My app keeps crashing since I started using a TextWatcher...
As you can see below i made a TextWatcher to 3 EditText fields...
And i made a button which listens to the 3 EditText..
If they are empty the button become disabled.
When the fields are filled the button should become enabled..
package com.example.magazijnapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.MenuPopupWindow;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.sql.Array;
public class MainActivity extends AppCompatActivity {
Spinner spinnermagazijn;
Button knop;
private EditText EditTextregisternummerbalk;
private EditText EditTextticketnummerbalk;
private EditText EditTextartikelnummerbalk;
private Button knopconfirm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditTextregisternummerbalk = findViewById(R.id.registernummerbalk);
EditTextticketnummerbalk = findViewById(R.id.ticketnummerbalk);
EditTextartikelnummerbalk = findViewById(R.id.artikelnummerbalk);
knopconfirm = findViewById(R.id.knop);
EditTextregisternummerbalk.addTextChangedListener(invulTextWatcher);
EditTextticketnummerbalk.addTextChangedListener(invulTextWatcher);
EditTextartikelnummerbalk.addTextChangedListener(invulTextWatcher);
}
private TextWatcher invulTextWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String registernummerinput = EditTextregisternummerbalk.getText().toString().trim();
String ticketnummerinput = EditTextticketnummerbalk.getText().toString().trim();
String artikelnummerinput = EditTextartikelnummerbalk.getText().toString().trim();
knopconfirm.setEnabled(!registernummerinput.isEmpty() && !ticketnummerinput.isEmpty() &&! artikelnummerinput.isEmpty());
}
#Override
public void afterTextChanged(Editable s) {
}
};
{
spinnermagazijn = findViewById(R.id.spinnermagazijn);
knop = findViewById(R.id.knop);
populatespinnermagazijn();
// Dit is het stukje voor de Knop afboeken waarmee je een melding genereerd, String aanpassen voor ander resultaat.
knop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, (R.string.succes), Toast.LENGTH_SHORT) .show();
}
});
}
// Dit gedeelte is voor de spinner.
private void populatespinnermagazijn() {
ArrayAdapter<String> magazijnenAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.steunpunten));
magazijnenAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnermagazijn.setAdapter(magazijnenAdapter);
}
}
And this is my logcat...
03-19 21:04:06.293 21151-21151/? E/libprocessgroup: failed to make and chown /acct/uid_10060: Read-only file system
03-19 21:04:06.293 21151-21151/? W/Zygote: createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
03-19 21:04:06.293 21151-21151/? I/art: Not late-enabling -Xcheck:jni (already on)
03-19 21:04:06.313 21151-21161/? I/art: Debugger is no longer active
03-19 21:04:06.351 21151-21151/? D/AndroidRuntime: Shutting down VM
03-19 21:04:06.354 21151-21151/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.magazijnapp, PID: 21151
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.magazijnapp/com.example.magazijnapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2236)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:149)
at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:99)
at android.content.Context.obtainStyledAttributes(Context.java:437)
at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:692)
at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:659)
at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:479)
at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:214)
at com.example.magazijnapp.MainActivity.<init>(MainActivity.java:73)
at java.lang.reflect.Constructor.newInstance(Native Method)
at java.lang.Class.newInstance(Class.java:1606)
at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2226)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
at android.app.ActivityThread.access$800(ActivityThread.java:151) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5254) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
03-19 21:04:07.996 21151-21151/? I/Process: Sending signal. PID: 21151 SIG: 9
There are two findViewById(R.id.knop);
remove this line:
knop = findViewById(R.id.knop);
and change :
knopconfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, (R.string.succes), Toast.LENGTH_SHORT) .show();
}
});
You are saying your app is crashing since you started using TextWatcher. So why don't you stop using it?
you can achieve the same thing without using TextWatcher by doing this.
knop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String registernummerinput = EditTextregisternummerbalk.getText().toString().trim();
String ticketnummerinput = EditTextticketnummerbalk.getText().toString().trim();
String artikelnummerinput = EditTextartikelnummerbalk.getText().toString().trim();
if((!registernummerinput.isEmpty() && !ticketnummerinput.isEmpty() &&! artikelnummerinput.isEmpty())) {
Toast.makeText(MainActivity.this, (R.string.succes), Toast.LENGTH_SHORT) .show();
}
}
});
you will not need any TextWathcer just modify the listner

Unable to instantiate activity: class com.pz.mediatonmessanger.ChatDialogActivity has no zero argument constructor

Errors and Chat Activity Dialog looks like this.
04-09 09:03:23.509 2722-2722/com.pz.mediatonmessanger E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.pz.mediatonmessanger, PID: 2722
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.pz.mediatonmessanger/com.pz.mediatonmessanger.ChatDialogActivity}: java.lang.InstantiationException: class com.pz.mediatonmessanger.ChatDialogActivity has no zero argument constructor
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.InstantiationException: class com.pz.mediatonmessanger.ChatDialogActivity has no zero argument constructor
at java.lang.Class.newInstance(Class.java:1563)
at android.app.Instrumentation.newActivity(Instrumentation.java:1065)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2199)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NoSuchMethodException: <init> []
at java.lang.Class.getConstructor(Class.java:531)
at java.lang.Class.getDeclaredConstructor(Class.java:510)
at java.lang.Class.newInstance(Class.java:1561)
at android.app.Instrumentation.newActivity(Instrumentation.java:1065)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2199)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Code
package com.pz.mediatonmessanger;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import com.pz.mediatonmessanger.Adapter.ChatDialogsAdapter;
import com.quickblox.auth.QBAuth;
import com.quickblox.auth.session.BaseService;
import com.quickblox.auth.session.QBSession;
import com.quickblox.chat.QBChatService;
import com.quickblox.chat.QBRestChatService;
import com.quickblox.chat.model.QBChatDialog;
import com.quickblox.core.QBEntityCallback;
import com.quickblox.core.exception.BaseServiceException;
import com.quickblox.core.exception.QBResponseException;
import com.quickblox.core.request.QBRequestBuilder;
import com.quickblox.core.request.QBRequestGetBuilder;
import com.quickblox.users.model.QBUser;
import java.util.ArrayList;
public class ChatDialogActivity extends AppCompatActivity {
FloatingActionButton floatingActionButton;
ListView lstChatDialogs;
public ChatDialogActivity(FloatingActionButton floatingActionButton) {
this.floatingActionButton = floatingActionButton;
}
public ChatDialogActivity(ListView lstChatDialogs) {
this.lstChatDialogs = lstChatDialogs;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_dialog);
createSessionForChat();
lstChatDialogs = (ListView)findViewById(R.id.lstChatDialogs);
loadChatDialogs();
floatingActionButton = (FloatingActionButton) findViewById(R.id.chatdialog_adduser);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ChatDialogActivity.this, ListUsersActivity.class );
startActivity(intent);
}
});
}
private void loadChatDialogs() {
QBRequestGetBuilder requestBuilder = new QBRequestGetBuilder();
requestBuilder.setLimit(100);
QBRestChatService.getChatDialogs(null,requestBuilder).performAsync(new QBEntityCallback<ArrayList<QBChatDialog>>() {
#Override
public void onSuccess(ArrayList<QBChatDialog> qbChatDialogs, Bundle bundle) {
//Kod
ChatDialogsAdapter adapter = new ChatDialogsAdapter(getBaseContext(),qbChatDialogs);
lstChatDialogs.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
#Override
public void onError(QBResponseException e) {
Log.e("Błąd",e.getMessage());
}
});
}
private void createSessionForChat() {
final ProgressDialog mDialog = new ProgressDialog(ChatDialogActivity.this);
mDialog.setMessage("Ładowanie...");
mDialog.setCanceledOnTouchOutside(false);
mDialog.show();
String user,password;
user = getIntent().getStringExtra("user");
password = getIntent().getStringExtra("password");
final QBUser qbUser = new QBUser(user,password);
QBAuth.createSession(qbUser).performAsync(new QBEntityCallback<QBSession>() {
#Override
public void onSuccess(QBSession qbSession, Bundle bundle) {
qbUser.setId(qbSession.getUserId());
try {
qbUser.setPassword(BaseService.getBaseService().getToken());
} catch (BaseServiceException e) {
e.printStackTrace();
}
QBChatService.getInstance().login(qbUser, new QBEntityCallback() {
#Override
public void onSuccess(Object o, Bundle bundle) {
mDialog.dismiss();
}
#Override
public void onError(QBResponseException e) {
Log.e("Błąd",""+e.getMessage());
}
});
}
#Override
public void onError(QBResponseException e) {
}
});
}
}
Activities don't have a constructor in Android, you can't create them as you do with other classes. They are instantiated by the system, all you need to do is to start them with context.startActivity(intent).
Remove all the constructors from this Activity and get a reference to the views with findViewById and you should be fine

Android Exception handling on EditText

I am going through an Android course online and have hit a stumbling block.
When an EditText (Number) field is submitted without any content, my app crashes.
I have tried adding exception handlers to the code, to my understanding. Nut I still have the same problem. I am handling the exceptions that show up in my logs, shown below.
The InvocationTargetException entry flags in Android Studio as Cannot resolve symbol InvocationTargetException.
I'm not sure what the problem is with that or if it might be related.
Code:
package com.example.richardcurteis.higherorlower;
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.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;
import java.lang.reflect.Method;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
int randomNumber;
EditText getUserInput;
public int getRandomNumber() {
Random randomGenerator = new Random();
randomNumber = randomGenerator.nextInt(10) +1;
return randomNumber;
}
public void higherOrLower(View view) {
String exceptionMessage = "";
try {
getUserInput = (EditText) findViewById(R.id.userInput);
} catch (InvocationTargetException e) {
exceptionMessage = "InvocationTargetException";
} catch (NumberFormatException e) {
exceptionMessage = "NumberFormatException";
} catch (IllegalStateException e) {
exceptionMessage = "IllegalStateException";
}
Toast.makeText(this, exceptionMessage, Toast.LENGTH_LONG).show();
int userInteger = Integer.parseInt(getUserInput.getText().toString());
String message = "";
if (userInteger > randomNumber) {
message = "Lower!";
getUserInput.getText().clear();
} else if (userInteger < randomNumber) {
message = "Higher!";
getUserInput.getText().clear();
} else {
message = "You win!";
getUserInput.getText().clear();
getRandomNumber();
}
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
randomNumber = getRandomNumber();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Errors:
12-28 16:36:23.985 5035-5035/com.example.richardcurteis.higherorlower E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.richardcurteis.higherorlower, PID: 5035
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:275)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:270)
at android.view.View.performClick(View.java:5198) 
at android.view.View$PerformClick.run(View.java:21147) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Caused by: java.lang.NumberFormatException: Invalid int: ""
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parseInt(Integer.java:358)
at java.lang.Integer.parseInt(Integer.java:334)
at com.example.richardcurteis.higherorlower.MainActivity.higherOrLower(MainActivity.java:40)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:270) 
at android.view.View.performClick(View.java:5198) 
at android.view.View$PerformClick.run(View.java:21147) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Use this helper method to convert string to integer
public static Integer toInteger(final String str, final Integer defaultValue) {
if (str == null) {
return defaultValue;
}
try {
return Integer.valueOf(str);
} catch (NumberFormatException nfe) {
return defaultValue;
}
}
Something like this
Integer userInteger = toInteger(getUserInput.getText().toString(), null);
if (userInteger == null) {
Toast.makeText(getApplicationContext(), "Invalid input", Toast.LENGTH_SHORT).show();
return;
}
Move into the "try" block this line of your code:
int userInteger = Integer.parseInt(getUserInput.getText().toString());
Looking through the error log it shows you're trying to parse a blank string to an int.
Caused by: java.lang.NumberFormatException: Invalid int: ""
InvocationTargetException is just a wrapper for an exception that's thrown within a dynamic invocation.
The exceptions are thrown because you're try catching around the wrong snippet of code.

How can I change the volume properly?

I have been stuck on this for way too long (4 hours yesterday, 3 hours today!) now. In my main menu screen, I have a mute button. I want it to call a method in my background service, which mutes all of the MediaPlayer audio that would be played in the background of my game.
Full code here
Here is something that might be causing the issue:
I am getting the error whenever the audio plays (which plays fine):
QCMediaPlayer mediaplayer NOT present
E/MediaPlayer﹕ Should have subtitle controller already set
package com.example.USERNAME.buttonsmasher;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
public class TwentySeconds extends Service {
static MediaPlayer ten;
static MediaPlayer three;
final String TAG = "MyCountdown";
static CountDownTimer cdt;
double millisUntilFinishedRounded;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Context context = this;
three = MediaPlayer.create(TwentySeconds.this, R.raw.threetwoone);
ten = MediaPlayer.create(TwentySeconds.this, R.raw.tenmoreseconds);
// ten = MediaPlayer.create(TwentySeconds.this, R.raw.tenmoreseconds);
// three = MediaPlayer.create(TwentySeconds.this, R.raw.threetwoone);
Log.v(TAG, "In start command");
cdt = new CountDownTimer(20000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
Log.v(TAG, millisUntilFinished + "left");
millisUntilFinishedRounded = (millisUntilFinished / 1000) * 1000;
if (millisUntilFinishedRounded == 10000) { //TEN SECONDS
// ten = MediaPlayer.create(TwentySeconds.this, R.raw.tenmoreseconds);
// while(ten == null){
ten = MediaPlayer.create(TwentySeconds.this, R.raw.tenmoreseconds);
// }
ten.start();
}
if (millisUntilFinishedRounded == 3000) {
/* Context context = this;
three = MediaPlayer.create(TwentySeconds.this, R.raw.threetwoone);
*/
// while(three == null){
three = MediaPlayer.create(TwentySeconds.this, R.raw.tenmoreseconds);
//}
three.start();
}
}
#Override
public void onFinish() {
Log.v(TAG, "Finished");
Intent intent = new Intent(TwentySeconds.this, GameOver.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Log.v(TAG, "About to start activity");
startActivity(intent);
}
};
cdt.start();
return START_STICKY;
}
public static void stopTimer() {
cdt.cancel();
}
public static void myMute() {
ten.setVolume(0, 0);
three.setVolume(0, 0);
}
public static void unMute() {
ten.setVolume(1, 1);
three.setVolume(1, 1);
}
#Override
public void onDestroy() {
stopSelf();
super.onDestroy();
}
}
_______________________________________________________________________________________________________________________________
Here is the method in Main_Menu (x starts as zero)
if ((x%2) == 0) { //If it's even
TwentySeconds.unMute();
Toast.makeText(Main_Menu.this, "UNMUTED", Toast.LENGTH_SHORT).show();
x++;
} else { //If its odd
TwentySeconds.myMute();
Toast.makeText(Main_Menu.this, "MUTED", Toast.LENGTH_SHORT).show();
x++;
}
__________________________________________________________________
Here is the stack trace:
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3842)
at android.view.View.performClick(View.java:4457)
at android.view.View$PerformClick.run(View.java:18491)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5272)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:883)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3837)
at android.view.View.performClick(View.java:4457)
at android.view.View$PerformClick.run(View.java:18491)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5272)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:883)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.USERNAME.buttonsmasher.TwentySeconds.myMute(TwentySeconds.java:106)
at com.example.USERNAME.buttonsmasher.Main_Menu.mute(Main_Menu.java:103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3837)
at android.view.View.performClick(View.java:4457)
at android.view.View$PerformClick.run(View.java:18491)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5272)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:883)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
at dalvik.system.NativeStart.main(Native Method)
I would really appreciate any feedback (positive or negative)!
Let me know if you need any thing else. Thanks so much for everything, I hope I can solve this issue... :)

Android Studio SeekBar Error

Hello I'm trying to get the value of a SeekBar in android studio. If i run app it is crashing. There is no syntax error.
package prosis.guiaturistico;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private static SeekBar seek_bar;
private static TextView text_view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
seekbar();
}
public void seekbar(){
seek_bar = (SeekBar)findViewById(R.id.seekbar);
text_view = (TextView)findViewById(R.id.seekbarValue);
text_view.setText("Covered : " + seek_bar.getProgress() + " / " +seek_bar.getMax());
seek_bar.setOnSeekBarChangeListener(
new SeekBar.OnSeekBarChangeListener(){
int progress_value;
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progress_value = progress;
text_view.setText("Covered : " + progress + " / " +seek_bar.getMax());
Toast.makeText(MainActivity.this,"SeekBar in progress",Toast.LENGTH_LONG).show();
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
Toast.makeText(MainActivity.this,"SeekBar in start",Toast.LENGTH_LONG).show();
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
text_view.setText("Covered : " + progress_value + " / " +seek_bar.getMax());
Toast.makeText(MainActivity.this,"SeekBar in stop",Toast.LENGTH_LONG).show();
}
}
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is my layout.
<SeekBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/seekbar"
android:layout_above="#+id/bt_pes"
android:layout_alignParentStart="true"
android:layout_alignEnd="#+id/bt_mon"
android:max="5000" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/seekbarValue"
android:layout_above="#+id/seekbar"
android:layout_below="#+id/bt_caf"
android:layout_alignEnd="#+id/bt_pes"
android:layout_alignStart="#+id/bt_pes" />
When I run I get these error messages and the emulator says that unfortunatly your program has stopped.
04-27 16:26:18.615 2846-2846/prosis.guiaturistico E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: prosis.guiaturistico, PID: 2846
java.lang.RuntimeException: Unable to start activity ComponentInfo{prosis.guiaturistico/prosis.guiaturistico.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.widget.SeekBar.getProgress()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at a android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.widget.SeekBar.getProgress()' on a null object reference
at prosis.guiaturistico.MainActivity.seekbar(MainActivity.java:27)
at prosis.guiaturistico.MainActivity.onCreate(MainActivity.java:21)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
    
The problem is this line:
text_view.setText("Covered : " + seek_bar.getProgress() + " / " +seek_bar.getMax());
Both seek_bar.getProgress() and seek_bar.getMax() return primitive int values. The TextView.setText() method tends to assume primitive int values to be Resource IDs.
To avoid this, use String.valueof() to convert primitive values to a String representation. Or better yet, use a StringBuilder instead of plain String concatenation.

Categories

Resources