I am trying to get values from shared preferences and it is returning null. The shared preference value is set from an asynctask. I tested it from inside the asynctask, printing the stord value in a toast and it worked, but problem is when I try the retrive the value outside the asynctask by clicking on the buttonRegister, it display null. There is no error shown into the logcat.
The code of the Activity:
package com.example.mohalogin;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Properties;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class RegisterActivity extends Activity {
private EditText editTextName;
private EditText editTextUsername;
private EditText editTextPassword;
private EditText editTextEmail;
private Button buttonRegister;
private Button buttonLogin;
//private Button gmail,yahoo;
Context context;
private SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyPreferences" ;
public static final String RegisResult = "result";
private static final String REGISTER_URL = "xxxxxxxxxx"; //fake data
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextUsername = (EditText) findViewById(R.id.editTextUserName);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
buttonRegister = (Button) findViewById(R.id.buttonRegister);
buttonLogin = (Button) findViewById(R.id.buttonLogin);
buttonRegister.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0){
registerUser();
sharedpreferences=getApplicationContext().getSharedPreferences("MyPrefs", getApplicationContext().MODE_PRIVATE);
buttonLogin.setText(sharedpreferences.getString("result","")); //testing by printing the value in the button
}
});
/*buttonLogin.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0){
startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
}
});*/
}
private void registerUser() {
String name = editTextName.getText().toString().trim().toLowerCase();
String username = editTextUsername.getText().toString().trim().toLowerCase();
String password = editTextPassword.getText().toString().trim().toLowerCase();
String email = editTextEmail.getText().toString().trim().toLowerCase();
register(name,username,password,email);
}
private void register(String name, String username, String password, String email) {
class RegisterUser extends AsyncTask<String, Void, String> {
ProgressDialog loading;
RegisterUserClass ruc = new RegisterUserClass();
private Context context2;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(RegisterActivity.this, "Please Wait","Registering new user", true, false);
}
#Override
protected String doInBackground(String... params) {
HashMap<String, String> data = new HashMap<String,String>();
data.put("name",params[0]);
data.put("username",params[1]);
data.put("password",params[2]);
data.put("email",params[3]);
String result = ruc.sendPostRequest(REGISTER_URL,data);
return result;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
sharedpreferences = context2.getSharedPreferences(MyPREFERENCES, context2.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(RegisResult, s);
editor.commit();
Toast.makeText(getApplicationContext(),sharedpreferences.getString("result",""), Toast.LENGTH_LONG).show();
}
public RegisterUser(Context context2)
{
this.context2=context2;
}
}
RegisterUser ru = new RegisterUser(getApplicationContext());
ru.execute(name, username, password, email);
}
}
Your problem is with the call to getSharedPreferences(String, int) -
You basically use two separate SharePreference instances, since you are passing a different name (String) for the SharedPreferences each time -
When you store the value, you are using
getSharedPreferences("MyPreferences", context2.MODE_PRIVATE);
And when you try to obtain the value, you are using
getSharedPreferences("MyPrefs", getApplicationContext().MODE_PRIVATE);
Modify your code to use the same SharedPreference name and it should work.
When you assign part of the code to be executed by the AsyncTask, it is actually executed in a new thread, other than the Ui thread. Actually in the onClick of the ButtonRegister, the registerUser() and the following two lines, run in parallel mode not sequentially.
If you want to make sure that saving in SharedPreferences is completed successfully, you can read it again and set the button text. Alter the OnPostExecute of your AsyncTask this way:
#Override
protected void onPostExecute(String s)
{
super.onPostExecute(s);
loading.dismiss();
.
.
.
buttonLogin.setText(sharedpreferences.getString("result",""));
}
You are accessing the value at the wrong place.
Try this code instead :)
package com.example.mohalogin;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Properties;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class RegisterActivity extends Activity {
private EditText editTextName;
private EditText editTextUsername;
private EditText editTextPassword;
private EditText editTextEmail;
private Button buttonRegister;
private Button buttonLogin;
//private Button gmail,yahoo;
Context context;
private SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyPreferences" ;
public static final String RegisResult = "result";
private static final String REGISTER_URL = "xxxxxxxxxx"; //fake data
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
sharedpreferences=getApplicationContext().getSharedPreferences("MyPrefs", getApplicationContext().MODE_PRIVATE);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextUsername = (EditText) findViewById(R.id.editTextUserName);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
buttonRegister = (Button) findViewById(R.id.buttonRegister);
buttonLogin = (Button) findViewById(R.id.buttonLogin);
buttonRegister.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0){
registerUser();
}
});
/*buttonLogin.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0){
startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
}
});*/
}
private void registerUser() {
String name = editTextName.getText().toString().trim().toLowerCase();
String username = editTextUsername.getText().toString().trim().toLowerCase();
String password = editTextPassword.getText().toString().trim().toLowerCase();
String email = editTextEmail.getText().toString().trim().toLowerCase();
register(name,username,password,email);
}
private void register(String name, String username, String password, String email) {
class RegisterUser extends AsyncTask<String, Void, String> {
ProgressDialog loading;
RegisterUserClass ruc = new RegisterUserClass();
private Context context2;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(RegisterActivity.this, "Please Wait","Registering new user", true, false);
}
#Override
protected String doInBackground(String... params) {
HashMap<String, String> data = new HashMap<String,String>();
data.put("name",params[0]);
data.put("username",params[1]);
data.put("password",params[2]);
data.put("email",params[3]);
String result = ruc.sendPostRequest(REGISTER_URL,data);
return result;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute();
loading.dismiss();
sharedpreferences = context2.getSharedPreferences(MyPREFERENCES, context2.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(RegisResult, s);
editor.commit();
Toast.makeText(getApplicationContext(),sharedpreferences.getString("result",""), Toast.LENGTH_LONG).show();
buttonLogin.setText(sharedpreferences.getString(RegisResult,"")); //testing by printing the value in the button
}
public RegisterUser(Context context2)
{
this.context2=context2;
}
}
RegisterUser ru = new RegisterUser(getApplicationContext());
ru.execute(name, username, password, email);
}
}
When you try to retrieve the value outside the asynctask, it display null because the asynctask didn't finish. Whatever you need to do with the data you get it in the executing of the asyncTask, you need to do it inside of onPostExecute, it is the only place where you can be sure the asyncTask already finish.
Re-instantiate your Shared-preference after the commit.
Related
This is the register fiile:
The error is when I stored data and after that, I log in when I click on the login button app got crushed.
this is the register section;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText textview1;
EditText textview2;
Button button1;
Button buttonlog;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview1 = (EditText)findViewById(R.id.ediuser);
textview2 = (EditText)findViewById(R.id.edipassword);
button1 = (Button)findViewById(R.id.btnreg);
buttonlog = (Button)findViewById(R.id.onlogin);
}
public void onreg(View view){
String username = textview1.getText().toString();
String Password = textview2.getText().toString();
sharedPreferences = getSharedPreferences("Dell", MODE_PRIVATE);
SharedPreferences.Editor editor1 = sharedPreferences.edit();
editor1.putString("username",username);
editor1.putString("password",Password);
editor1.apply();
Toast.makeText(this, "Register Successfully", Toast.LENGTH_SHORT).show();
}
public void onlog(View view){
Intent intent = new Intent(this,login.class);
startActivity(intent);
}
}
this is the login file:
package com.example.newshrd;
import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class login extends AppCompatActivity {
EditText editText1;
EditText editText2;
Button button2;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
editText1 = (EditText) findViewById(R.id.userlog);
editText2 = (EditText) findViewById(R.id.passwordlog);
button2 = (Button) findViewById(R.id.btnlog);
sharedPreferences = getSharedPreferences("Dell", MODE_PRIVATE);
}
//this is the login section find error and let me know please
public void onloghere(View view){
String userlog = editText1.getText().toString();
String passlog = editText2.getText().toString();
String userlogin= sharedPreferences.getString("username",null);
String userpaswwords=sharedPreferences.getString("passowrd",null);
if (userlog.contains(userlogin) && passlog.contains(userpaswwords)){
Toast.makeText(this, "Your are in", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, "You are not", Toast.LENGTH_SHORT).show();
}
}
}
please, someone, find the error and let me know what I am missing in this code.
It is properly formatted (at least by the preview it is), so how can I fix this? I'm new to Stack Overflow formatting.
When you save, key is "password":
editor1.putString("password",Password);
But when get, you have a typo for the key here "passowrd":
String userpaswwords=sharedPreferences.getString("passowrd",null);
The userpaswwords you get is null (you set SharedPreferences.getString(String key, #Nullable String defValue) defValue value to be null), and here crashes:
passlog.contains(userpaswwords)
Cuz String.contains(CharSequence s) needs the argument to be non-null.
i tried to make my first converter in android studio with java but 2 functions setText and getText are not working
package com.example.unitconvertor;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity<editTextTextPersonName> extends AppCompatActivity {
private Button button;
private editTextTextPersonName editTextTextPersonName;
private View editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "value saved", Toast.LENGTH_SHORT).show();
String s = editText.getText().toString();
int inch = Integer.parseInt(s);
double cm = 2.54 * inch;
editText.setText( "the value is" + cm);
}
});
}
}
i hope that i am clear
thankyou
Try this-
public class MainActivity extends AppCompatActivity {
private Button button;
private EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
editText = findViewById(R.id.your_id);//ADD YOUR EDIT TEXT ID HERE
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "value saved", Toast.LENGTH_SHORT).show();
String s = editText.getText().toString();
int inch = Integer.parseInt(s);
double cm = 2.54 * inch;
editText.setText( "the value is" + cm);
}
});
}
}
The error is that your "edittext" is declared as view, correct it like this : private EditText edittext;
then, retrieve it by id like this in your onCreate method edittext = findViewById(R.id.your_id);
I'm trying to pass a value from an ArrayList in one Activity (LensActivity) to a TextView on my MainActivity. On this site i found the Intent method and was experimenting with that, but seem unable to pass it, the info is getting fetched in the String lensString, and passed to the Intent, but in Main Activity seems to not be passing or getting on the TextView, and in some experiments, since the getIntent is on MainActivity, i got a null pointer.
Here is the code for the LensActivity which has the Button that send the info.
package com.komorebiestudio.cam_report_funcionality;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class LensActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private LensAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private TextView LensChange;
private String lensString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lens_activity);
Intent lensIntent = new Intent(LensActivity.this,MainActivity.class);
lensIntent.putExtra("LensIntent",lensString);
final ArrayList <LensItem> lensList = new ArrayList<>();
lensList.add(new LensItem(R.drawable.zeiss,"24mm","Zeiss Compact Prime"));
lensList.add(new LensItem(R.drawable.ic_camera,"35mm","Angenieux"));
lensList.add(new LensItem(R.drawable.cooke,"50mm","Cooke S5I"));
mRecyclerView = findViewById(R.id.lens_list);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new LensAdapter(lensList);
LensChange = findViewById(R.id.lensinfo);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
final Intent ChangeLens = new Intent(this, MainActivity.class);
mAdapter.setOnItemClickListener(new LensAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
//Crea String con la informacion de posicion y texto del lente
String lensPosition = lensList.get(position).getLens();
lensString = lensPosition;
Toast.makeText(getApplicationContext(),"this is " + lensString , Toast.LENGTH_SHORT).show();
startActivity(new Intent(LensActivity.this,MainActivity.class));
}
});
}
}
and here is the code of the MainActivity that receives it.
package com.komorebiestudio.cam_report_funcionality;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements FpsDialog.FpsDialogListener{
private TextView textViewinfo1;
private Button button1;
private Button lensButton;
private TextView lensInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lensInfo = findViewById(R.id.lensinfo);
lensInfo.setText(getIntent().getStringExtra("LensIntent"));
textViewinfo1 = findViewById(R.id.info1);
button1 = findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
openDialog();
}
});
lensButton = findViewById(R.id.lensbutton);
lensButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,LensActivity.class));
}
});
}
public void openDialog(){
FpsDialog fps_dialog = new FpsDialog();
fps_dialog.show(getSupportFragmentManager(),"Fps Dialog");
}
#Override
public void applyText(String fpsinfo) {
textViewinfo1.setText(fpsinfo);
}
}
In your LensActivity, you're creating an Intent that you never use. The Intent is this one:
Intent lensIntent = new Intent(LensActivity.this,MainActivity.class);
lensIntent.putExtra("LensIntent",lensString);
Instead, you should create it in the Item Click Listener. Just remove the code above, and modify the listener in this way:
mAdapter.setOnItemClickListener(new LensAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
//Crea String con la informacion de posicion y texto del lente
String lensPosition = lensList.get(position).getLens();
lensString = lensPosition;
Intent lensIntent = new Intent(LensActivity.this,MainActivity.class);
lensIntent.putExtra("LensIntent",lensString);
Toast.makeText(getApplicationContext(),"this is " + lensString , Toast.LENGTH_SHORT).show();
startActivity(lensIntent);
}
});
You need to use the putExtra method after you assign a value to the variable lensString
mAdapter.setOnItemClickListener(new LensAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
//Crea String con la informacion de posicion y texto del lente
String lensPosition = lensList.get(position).getLens();
lensString = lensPosition;
lensIntent.putExtra("LensIntent",lensString);
Toast.makeText(getApplicationContext(),"this is " + lensString , Toast.LENGTH_SHORT).show();
// Notice that you are not using your previously created intent in you
// original code.
startActivity(lensIntent);
}
});
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
Hi i am doing a project that is due wednesday and i have spent over 13 hours trying to get Android studio working again, first their was a problem with the gradle and now i keep getting a nullpointerexception even though it same code that was working before. here is the code, please help? because i am stuck and could be doing my project rather that trying to solve android studios problems. by the way there are no errors within the code it says but here is the code.
package ie.wit.fitnessmadeeasy;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LogActivity extends AppCompatActivity {
DataBaseHelper helper = new DataBaseHelper(this);
EditText uname = (EditText) findViewById(R.id.et_username);
String unstr = uname.getText().toString();
EditText pass = (EditText) findViewById(R.id.et_password);
String passstr = pass.getText().toString();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log);
TextView registerLink = (TextView) findViewById(R.id.regHere); //register link creates a link between the two pages
registerLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registerIntent = new Intent(LogActivity.this, RegisterActivity.class);
LogActivity.this.startActivity(registerIntent); //what this does it creates an intent that opens the registeravtivity then it tells the current activity to perform the intent and open the register page
}
});
}
// Button login = (Button) findViewById(R.id.login);
public void onLogClick(View view) {
if (view.getId() == R.id.login) {
String Password = helper.searchPassstr(unstr);
Log.v("pass", passstr);
Log.v("pass", Password);
if (passstr.equals(Password)) {
Intent i = new Intent(LogActivity.this, UserAreaActivity.class);
i.putExtra("username", unstr);
startActivity(i);
} else {
Toast temp = Toast.makeText(LogActivity.this, "Username and Password don't Match", Toast.LENGTH_SHORT);
temp.show();
}
}
}
}
package ie.wit.fitnessmadeeasy;
import android.content.Intent;
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.Toast;
public class RegisterActivity extends AppCompatActivity {
DataBaseHelper helper = new DataBaseHelper(this);
final EditText name = (EditText) findViewById(R.id.et_name);
final EditText username = (EditText) findViewById(R.id.et_username);
final EditText password1 = (EditText) findViewById(R.id.et_password);
final EditText password2 = (EditText) findViewById(R.id.et_password);
String namestr = name.getText().toString();
String usernamestr = username.getText().toString();
String password1str = password1.getText().toString();
String password2str = password2.getText().toString();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
// final EditText password2 = (EditText) findViewById(R.id.et_password);
name.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(name.getText().length()==0){
name.setError("Fill Out");
}
else if(username.getText().length()==0){
username.setError("Fill Out");
}
}
});
}
public void onRegClick(View v)
{
if(v.getId() == R.id.confirm)
{
// EditText age = (EditText) findViewById(R.id.et_age); //age is a final variable and is only assigned to activity_register as a view
// EditText name = (EditText) findViewById(R.id.et_name);
// EditText username = (EditText) findViewById(R.id.et_username);
// EditText password1 = (EditText) findViewById(R.id.et_password);
// EditText password2 = (EditText) findViewById(R.id.et_password2);
if(namestr.equals("")){
Toast pass = Toast.makeText(RegisterActivity.this, "Enter Name!", Toast.LENGTH_SHORT);
pass.show();
}
if(usernamestr.equals("")){
Toast pass = Toast.makeText(RegisterActivity.this, "Enter Username!", Toast.LENGTH_SHORT);
pass.show();
}
if(password1str.equals("")){
Toast pass = Toast.makeText(RegisterActivity.this, "Enter Password!", Toast.LENGTH_SHORT);
pass.show();
}
if(!password1str.equals(password2str))
{
//popup message
Toast pass = Toast.makeText(RegisterActivity.this, "Passwords don't match!", Toast.LENGTH_SHORT);
pass.show();
}
else{
// String namestr = name.getText().toString();
//insert details
RegRequest reg = new RegRequest();
reg.setEt_name(namestr);
reg.setEt_username(usernamestr);
reg.setEt_password(password1str);
// r.setEt_age(agestr);
Toast success = Toast.makeText(RegisterActivity.this, "Success", Toast.LENGTH_SHORT);
success.show();
Intent i = new Intent(RegisterActivity.this, LogActivity.class);
startActivity(i);
helper.insertUser(reg);
}
}
}
}
package ie.wit.fitnessmadeeasy;
public class RegRequest{
String et_name , et_username, et_password;
// int et_age;
public void setEt_name(String et_name)
{
this.et_name = et_name;
}
public String getEt_name()
{
return this.et_name;
}
public void setEt_username(String et_username)
{
this.et_username = et_username;
}
public String getEt_username()
{
return this.et_username;
}
public void setEt_password(String et_password)
{
this.et_password = et_password;
}
public String getEt_password()
{
return this.et_password;
}
}
at ie.wit.fitnessmadeeasy.LogActivity.<init>(LogActivity.java:17)
LogActivity.java
Only declare the fields like the following:
EditText uname, pass;
String unstr, passstr;
Initialize in onCreate() method.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log);
uname = (EditText) findViewById(R.id.et_username);
unstr = uname.getText().toString();
pass = (EditText) findViewById(R.id.et_password);
passstr = pass.getText().toString();
}
And RegisterActivity.java
DataBaseHelper helper ;
EditText name, username,password1,password2;
String namestr,usernamestr,password1str,password2str;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
helper = new DataBaseHelper(this);
name = (EditText) findViewById(R.id.et_name);
username = (EditText) findViewById(R.id.et_username);
password1 = (EditText) findViewById(R.id.et_password);
password2 = (EditText) findViewById(R.id.et_password);
namestr = name.getText().toString();
usernamestr = username.getText().toString();
password1str = password1.getText().toString();
password2str = password2.getText().toString();
}
I'm trying to build an app, that pastes an input from a previous activity(works with no problem) and then shows me some things from a database(when ButtonGet is pressed). The problem is that when I try to Run the project, I get
Java.lang.IllegalStateException: Already attached. What is wrong with my code?
package br.exemplozxingintegration;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class SecondActivity extends AppCompatActivity implements View.OnClickListener {
private EditText pastetext;
private ClipboardManager myClipboard;
private ClipData myClip;
private Button btn;
private EditText textView1;
private Button buttonGet;
private TextView textViewResult;
private ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
pastetext = (EditText) findViewById(R.id.textView1);
btn = (Button)findViewById(R.id.buttonPaste);
btn.performClick();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1 = (EditText) findViewById(R.id.textView1);
buttonGet = (Button) findViewById(R.id.buttonGet);
textViewResult = (TextView) findViewById(R.id.textViewResult);
buttonGet.setOnClickListener(this);
}
#SuppressLint("NewApi")
public void paste(View view) {
ClipData cp = myClipboard.getPrimaryClip();
ClipData.Item item = cp.getItemAt(0);
String text = item.getText().toString();
pastetext.setText(text);
Toast.makeText(getApplicationContext(), "Text Pasted",
Toast.LENGTH_SHORT).show();
}
private void getData() {
String id = textView1.getText().toString().trim();
if (id.equals("")) {
Toast.makeText(this, "", Toast.LENGTH_LONG).show();
return;
}
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
String url = Config.DATA_URL+textView1.getText().toString().trim();
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(SecondActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response){
String name="";
String image = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
name = collegeData.getString(Config.KEY_NAME);
image = collegeData.getString(Config.KEY_IMAGE);
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult.setText("Name:\t"+name+"\nImagine :\t"+ image);
}
#Override
public void onClick(View v) {
getData();
}
}
In your onCreate, you're calling super.onCreate() twice, and also setContentView() twice. I'm pretty sure that's not what you want to do.
Problem is you first initialize textView1, and perform the button click, at that point you are just resetting any previous settings by calling onCreate() again, and before perfomClick methods hits getData() method, inside here also tries to access the text from textView1 but you called onCreate after that and set the view from scratch. That is why you cannot get it work, delete the duplicate code
Please attach logcat message and if possible DB file.
This could be the possible problem, You might be reassign the already assigned db object while inserting in the table.
If none of the answers here helped - and the Log message makes no sense - I recommend you to File->Invalidate cahce
then run the app again and hopefully this time the log will show the correct stack trace.