Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
This is my first post at StackExchange.
I am a very beginner Android developer. I was making an app for saving arrays(lists). But unfortunately when I run my app it shows {Unfortunately, Shop has stopped!}. I am pretty much familiar with this error and many times I have also been able to get through it. But this time, I can't figure out what am I doing wrong. My code looks perfect but somehow keeps showing that error.
I am pasting my java code below. Please go through my code and point my mistake! PLEASE~!
AddItem.java
package com.rcube.shop;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AddItem extends Activity{
SharedPreferences store = PreferenceManager.getDefaultSharedPreferences(getApplication());
SharedPreferences.Editor edit = store.edit();
ArrayList<String> itemarray = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.add_item);
Button addnewitem = (Button) findViewById(R.id.addnewitem);
final EditText getitemname = (EditText)findViewById(R.id.getitem);
addnewitem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String newitemname = getitemname.getText().toString();
if(newitemname.length()!=0){
itemarray.add(newitemname);
Set<String> itemset = new HashSet<String>(itemarray);
edit.putStringSet("items_set", itemset);
edit.commit();
}else{
Toast.makeText(AddItem.this, "Write Item name before submitting!", Toast.LENGTH_LONG).show();
}
}
});
}
}
Please tell me what am I doing wrong. And I have add new android activity in Android Manifest also, so this error is not because of that.
Thanks again!
PEACE~!
Seems like you are getting NPE at getApplicationContect()
Put this in onCreate after setContentView
SharedPreferences store = PreferenceManager.getDefaultSharedPreferences(getApplication());
SharedPreferences.Editor edit = store.edit();
You won't get context before that.
Hope this helps.
Put these 2 lines inside onCreate() after findViewById, then you can use context.
SharedPreferences store = PreferenceManager.getDefaultSharedPreferences(getApplication());
SharedPreferences.Editor edit = store.edit();
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 12 months ago.
Improve this question
I am a bit new to Android Studio and Java. I am trying to update a text by replacing it from an element of an ArrayList. However, when using setText(userList.get(0)), the app crashes. My guess is that the arraylist is empty or cannot be accessed. But I use the same code on a button with a setOnClickListener, the text is updated by the string found in the arrayList.
I want to make the app automatically update the Text onloading the activity.
Here is my MainActivity.java -- I commented the setText that is crashing the app.
package com.example.sampletest;
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<String> userList = new ArrayList<String>();
TextView text;
Button swapText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new getUsers().execute();
text = (TextView) findViewById(R.id.text);
swapText = (Button) findViewById(R.id.button);
//text.setText(userList.get(0));
swapText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text.setText(userList.get(0));
}
});
}
class getUsers extends AsyncTask<Void, Void, Void> {
String error = "";
#Override
protected Void doInBackground(Void... voids) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://192.168.100.5:3306/cardetailingdb", "lau", "lau");
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM users");
while (resultSet.next()) {
userList.add(resultSet.getString(1));
}
} catch (Exception e) {
error = e.toString();
}
return null;
}
}
}
My guess is that the arraylist is empty or cannot be accessed.
The list is empty. You can see the stacktrace in the logcat for crash details.
But I use the same code on a button with a setOnClickListener, the text is updated by the string found in the arrayList.
That's because it's is not executed syncronously in onCreate() but later on clicking the button.
I want to make the app automatically update the Text onloading the activity.
You can add an onPostExecute() to your async task that gets run on the main thread once the background call completes. You should also check that the async call actually succeeded and not blindly trust that userList has elements in it.
In type of async task you should ensured first your all data is populated. Soo make sure background is completed and List is not empty. Hope will be work fine. For crashing issues you can add a check point like:
if(userList.size()>0){ text.setText(userList.get(0)); }
Hi I'm currently trying to save a simple integer value from an EditText to sharedPreferences so that I can access it within any activity. I've tried following the google tutorials but I was unable to make it work. I ended up getting the error message "Cannot resolve method 'getPreferences' ". I realize that there have been other threads about sharedPreferences but I cannot seem to make sense of them.
Also, if you can help me find a better way than my catch statement to avoid the NumberFormatException, please let me know. Thanks again!Any help is much appreciated!
Java
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import static com.managergmail.time.finite.finitemanager02.R.id.textViewTest;
public class ExamPrepHome extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exam_prep_home);
Button buttonSaveNumberOfExams = (Button) findViewById(R.id.buttonSaveNumberOfExams);
try{
final EditText numberOfExamsInput = (EditText) findViewById(R.id.numberOfExamsInput);
final int numberOfExamsValue = Integer.valueOf(numberOfExamsInput.getText().toString());
buttonSaveNumberOfExams.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_number_of_exams), numberOfExamsValue);
editor.commit();
}
});
}catch(NumberFormatException ex){
System.out.println("Value at TextView is not a valid integer");
}
}
}
Instead of
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
use SharedPreferences sharedPref = ExamPrepHome.this.getPreferences(Context.MODE_PRIVATE);
Reason for this is because inside the anonymous class, 'this' represents that inner class and not the Activity object. And you have to use number format exception to check to avoid crashes when you retrieve the object.
I am writing a code for going to the next page after clicking a button so I have written the code that I have mentioned below i just want to confirn that it is correct as i cant check it now, I know this is silly but I need help
package com.example.myfirstapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class DetailsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
Button btnNextScreen = (Button) findViewById(R.id.btnNextScreen);
btnNextScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent nextScreen = new Intent(getApplicationContext(), JewelInfo.class);
// TODO Auto-generated method stub
startActivity(nextScreen);
}
});
}
}
Assuming that your JewelInfo extends from an Activty it looks fine.
I think you should use Intent nextScreen = new Intent(DetailsActivity.this, JewelInfo.class); instead of getApplicationContext()
The correctness of code is never checked just by looking at a bit of code. Syntactically, it seems to not contain an error. Semantically, how should we know? You need to define what you want to do, how you want it to look, etc. Basically, what are the requirements?
We can then validate the code against the requirements but not assess the correctness as that is only discerned by executing the code and evaluating the result of the execution on the device it is executed against the requirements.
use DetailsActivity.this instead of getApplicationContext(), and declare your JewelInfo activity on the manifest file : <activity android:name=".JewelInfo" />.Check this tutorial about how to switch between activities and pass data between them
I have huge problem. Have searching answer from many places but I do not find answer to question.
I have 2 classes in java. One is "main" and other is "menu"
On main, there is editText where person can type name and button ok.
When you press ok, I want to specific thing happen. That is where I need help. I am newcomer in Android.
I want that in other class, where will be main application and stuff, the entered name would be displayed. For example "Welcome " + name
I have tried many ways but I do not get it to work. So I want it to get one of 2 possible ways.
Set string in class 1 and then when it goes class 2, then it imports the string from class 1 to class 2 so I can use it.
I set string in class 2 and then in Class 1 I change the string in class 2, so the main 'data' string is actually in class 2, where I will continue using it if needed!
I have searched it from many places, used google and this database, but haven't found answer.
My codes are really nothing much, so no point pasting them here :).
Thanks for the help!
edit:// Ok, here are some codes then :)
package viimane.voimalus.incule;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class ViimaneVoimalusActivity extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button oknupp = (Button) findViewById(R.id.nimiOK);
oknupp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("viimane.voimalus.in" +cule.REALMENU"));
}
});
}
}
package viimane.voimalus.incule;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
public class RealMenu extends Activity {
EditText nimesisestus;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.peamenu);
}
}
You didn't show any code at all, so the answer won't be too detailed.
You can pass a String in the intent used to start the second activity, using putExtra method. In the second activity you may get the string by calling getStringExtra(). If you don't know much about starting activity and intents, there are many resources on the web, for example - this one.
To receive text input use EditText and to put text on the screen (that the user can't cange) use TextView.
Those are starting points. Next time I hope the question will be more focused.
Pass the string as parameter to the constructor of the menu class like this:
menu m = new menu(mystring);
then in the constructor save the atribute to your class
private String mystring;
menu(String mystring)
{
this.mystring = mystring;
}
What I want is that when Activity starts first time, it first checks if nimiolemas is true. Since it just starts, then it can't be true. So, it will automatically starts new activity and also asks to get me info. In activity 2 person can type their name and when they press Ok, info will be sent back to activity one. Now, I don't know really how to change there Boolean to true and send that as well, so for now I told to change nimiolemas true before launching activity 2.
After pressing ok, it sends back to activity one and does the check again. Since it should be now true and also able to retrieve information about persons name, then it will go to true condition and print that name on screen in first activity. Now whenever program is launched, it will skip asking name and will straight show the person name :).
But it doesn't work exactly as I want. Before i put boolean, it actually went to second activity, but I couldn't get data so well. I have been working on solution for too long and I really appreciate help. If I find mistakes I can study from that more then searching on solution all over internet for next 10 hours :(.
I might have made some things very wrong, so please let me know and teach me! I really want to get better in this! So far I have done:
package viimane.voimalus;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class MainStuff extends Activity {
String tyybinimi;
TextView tere;
Boolean nimiolemas;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
tere = (TextView) findViewById(R.id.TERE);
Intent i = new Intent(this, nimekysija.class);
tyybinimi = i.getStringExtra("nimi");
if (nimiolemas = true) {
System.out.print(tyybinimi);
} else {
startActivity(i);
nimiolemas = true;
finish();
}
}
}
package viimane.voimalus;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
package viimane.voimalus;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class nimekysija extends Activity {
Intent resultIntent;
EditText nimi;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.nimekysija);
Button kysOk = (Button) findViewById(R.id.bNimekysija);
nimi = (EditText) findViewById(R.id.etNimekysija);
kysOk.setOnClickListener(new View.OnClickListener() {
String nimiS = nimi.getText().toString();
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent();
i.putExtra("nimi", nimiS);
startActivity(new Intent("viimane.voimalus.MAIN"));
finish();
}
});
}
}
Instead of using a boolean, you should be using Shared Preferences.