Unfortunately, the app has stopped Android Studio - java

I am pretty sure there is no problem in my XML or manifest. The problem has to be in my code (because I had altered my code slightly and it stopped working). The app crashes before it even begins. The error I got is:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.trainer.braintrainer/com.trainer.braintrainer.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.Button.setText(java.lang.CharSequence)' on a null
object reference
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
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.NullPointerException: Attempt to invoke virtual
method 'void android.widget.Button.setText(java.lang.CharSequence)' on
a null object reference
at
com.trainer.braintrainer.MainActivity.generateQuestion(MainActivity.java:60)
at
com.trainer.braintrainer.MainActivity.onCreate(MainActivity.java:101)
at android.app.Activity.performCreate(Activity.java:6237)
at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
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)  06-16
08:01:16.547 24091-24091/com.trainer.braintrainer I/Process: Sending
signal. PID: 24091 SIG: 9
Below is my Main java code:
package com.trainer.braintrainer;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
ArrayList<Integer> answers=new ArrayList<Integer>();
Random rand = new Random();
int locationOfCorrectAnswer;
Button startButton;
Button button0;
Button button1;
Button button2;
Button button3;
int score=0;
int numberOfQuestions=0;
TextView answerMessage;
String message;
TextView scoreText;
TextView sumTextView;
TextView timerText;
public void generateQuestion(){
int a=rand.nextInt(21);
int b=rand.nextInt(21);
sumTextView.setText(Integer.toString(a) + " + " + Integer.toString(b));
locationOfCorrectAnswer=rand.nextInt(4);
answers.clear();
int inCorrectAns;
for (int i=0;i<=3;i++){
if (i==locationOfCorrectAnswer){
answers.add(a+b);
}else{
inCorrectAns=rand.nextInt(50);
while (inCorrectAns==a+b){
inCorrectAns=rand.nextInt(50);
}
answers.add(inCorrectAns);
}
}
button0.setText(Integer.toString(answers.get(0)));
button1.setText(Integer.toString(answers.get(1)));
button2.setText(Integer.toString(answers.get(2)));
button3.setText(Integer.toString(answers.get(3)));
}
public void startButton(View view){
startButton.setVisibility(View.INVISIBLE);
}
public void answerFunction(View view){
int tappedLocation= (int)view.getTag();
if (tappedLocation==locationOfCorrectAnswer){
message="Correct!";
score++;
}else{
message="Wrong!";
}
answerMessage.setText(message);
scoreText.setText(Integer.toString(score) + "/" + Integer.toString(numberOfQuestions));
numberOfQuestions++;
generateQuestion();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startButton=(Button)findViewById(R.id.button5);
answerMessage=(TextView)findViewById(R.id.messageView);
sumTextView=(TextView)findViewById(R.id.sumTextView);
scoreText=(TextView)findViewById(R.id.scoreText);
timerText=(TextView)findViewById(R.id.timerText);
generateQuestion();
new CountDownTimer(30100,1000){
#Override
public void onTick(long millisUntilFinished) {
int seconds=(int) millisUntilFinished/1000;
timerText.setText(Integer.toString(seconds)+"s");
}
#Override
public void onFinish() {
answerMessage.setText("Done");
}
}.start();
button0=(Button)findViewById(R.id.ans1);
button1=(Button)findViewById(R.id.ans2);
button2=(Button)findViewById(R.id.ans3);
button3=(Button)findViewById(R.id.ans4);
}
}

You are calling the method generateQuestion(); before assigning value to the buttons: button1, button2 etc. When you do setText on these buttons, it throws a null object reference error. what you can do is:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startButton=(Button)findViewById(R.id.button5);
answerMessage=(TextView)findViewById(R.id.messageView);
sumTextView=(TextView)findViewById(R.id.sumTextView);
scoreText=(TextView)findViewById(R.id.scoreText);
timerText=(TextView)findViewById(R.id.timerText);
button0=(Button)findViewById(R.id.ans1);
button1=(Button)findViewById(R.id.ans2);
button2=(Button)findViewById(R.id.ans3);
button3=(Button)findViewById(R.id.ans4);
generateQuestion();
new CountDownTimer(30100,1000){
#Override
public void onTick(long millisUntilFinished) {
int seconds=(int) millisUntilFinished/1000;
timerText.setText(Integer.toString(seconds)+"s");
}
#Override
public void onFinish() {
answerMessage.setText("Done");
}
}.start();
}
}
That is assign the respective views to the button before calling the generateQuestion()

Related

Problem with Android Networking (Using Google Book API and LoadManager/ AsyncTaskLoader)

Having problems debugging an android networking application. I think I might have some problems with the import but I don't know which. If you can see the problem, please do let me know. Thank you.
MainActivity.java
package com.example.networkingfinals;
import androidx.appcompat.app.AppCompatActivity;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Loader;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.util.List;
public class MainActivity extends AppCompatActivity implements LoaderCallbacks<List<BookInfo>> {
private String url;
private String input;
private BookAdapter bookAdapter;
private int LOADER_ID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.submit);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editText = (EditText) findViewById(R.id.input);
input = String.valueOf(editText.getText());
url = "https://www.googleapis.com/books/v1/volumes?q="+input+"&maxResults=3";
}
});
LoaderManager loaderManager = getLoaderManager();
getLoaderManager().initLoader(LOADER_ID, null, this);//Set loader manager to call asyncloader in onCreateLoader
//TODO: Implement AsyncTaskLoader and LoadManager fetching network data on parallel thread
}
#Override
public Loader<List<BookInfo>> onCreateLoader(int id, Bundle args) {
Loader<List<BookInfo>> books = new BookAsync(this, url);
return books;
//Call oncreate Loader , fetching List of Book Info
}
#Override
public void onLoadFinished(Loader<List<BookInfo>> loader, List<BookInfo> data) {
Log.v("onLoadFinished", "Return " + data);
bookAdapter.addAll(data);
}
#Override
public void onLoaderReset(Loader loader) {
bookAdapter.clear();
}
Logcat
2021-01-10 18:44:55.950 13590-13590/com.example.networkingfinals V/onCreateLoader: Return BookAsync{814c192 id=0}
2021-01-10 18:44:56.045 13590-13590/com.example.networkingfinals V/onLoadFinished: Return null
2021-01-10 18:44:56.045 13590-13590/com.example.networkingfinals D/AndroidRuntime: Shutting down VM
2021-01-10 18:44:56.055 13590-13590/com.example.networkingfinals E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.networkingfinals, PID: 13590
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.networkingfinals.BookAdapter.addAll(java.util.Collection)' on a null object reference
at com.example.networkingfinals.MainActivity.onLoadFinished(MainActivity.java:61)
at com.example.networkingfinals.MainActivity.onLoadFinished(MainActivity.java:17)
at android.app.LoaderManagerImpl$LoaderInfo.callOnLoadFinished(LoaderManager.java:497)
at android.app.LoaderManagerImpl$LoaderInfo.onLoadComplete(LoaderManager.java:465)
at android.content.Loader.deliverResult(Loader.java:157)
at android.content.AsyncTaskLoader.dispatchOnLoadComplete(AsyncTaskLoader.java:274)
at android.content.AsyncTaskLoader$LoadTask.onPostExecute(AsyncTaskLoader.java:97)
at android.os.AsyncTask.finish(AsyncTask.java:755)
at android.os.AsyncTask.access$900(AsyncTask.java:192)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:772)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7458)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:935)
2021-01-10 18:44:56.138 13590-13590/com.example.networkingfinals I/Process: Sending signal. PID: 13590 SIG:
I think I don't understand how onCreateLoader() and onLoadFinished() works. I tried and find that onCreateLoader return non-null data but in onLoadFinished() the data passed into it was null.
This error is because your adapter is not initialized yet you need to initialize it in onCreate
this.bookAdapter = new BookAdapter();
the error message says
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.networkingfinals.BookAdapter.addAll(java.util.Collection)' on a null object reference
that means is your adapter is null and you call addAll from the null object reference

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

Max Bench Press Calculator Project not working

I want the text view to increase by 2.5 every button press, but the app keeps crashing. I tried using the number picker, but I didn't like the way it was oriented vertically. I decided to make my own and later I add the long press capabilities, but now I am experimenting with the buttons.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements OnClickListener {
private Button Calculate;
private Button plus;
private Button menus;
private OnClickListener buttonclick;
private TextView textView;
int startweight;
double weight;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
menus = (Button) findViewById(R.id.button3);
plus = (Button) findViewById(R.id.button2);
Calculate = (Button) findViewById(R.id.button);
menus.setOnClickListener(this);
plus.setOnClickListener(this);
Calculate.setOnClickListener(this);
int startweight = 100;
textView.setText("" + startweight );
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.button2:
if (weight != 100) {
weight = weight +2.5;
}
else{
weight = startweight - 2.5;
}
textView.setText("" + weight);
break;
case R.id.button3:
if (weight != 100) {
weight = weight - 2.5;
}
else{
weight = startweight -2.5;
}
textView.setText("" + weight);
break;
case R.id.button:
break;
}
}
}
This is the stack from the logcat:
FATAL EXCEPTION: main
Process: com.example.luke.maxbenchcalculator, PID: 2281
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.luke.maxbenchcalculator/com.example.luke.maxbenchcalculator.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
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.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.luke.maxbenchcalculator.MainActivity.onCreate(MainActivity.java:39)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
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)
You never assigned a value to the textView member, so it stays null. Then you try to call a method on it during onCreate, which causes a crash. Assign it a value and make sure it's not null before calling a method on it.

Android Studio can't find Resuorces

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

Categories

Resources