The problem is alertdialogue box not at all working and it crashes everytime
I checked each and every line with youtube,
but it cant be helped
here's the code:
public void showupdatedialogue(String id , String name){
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = getLayoutInflater();
View dialog = inflater.inflate(R.layout.update,null);
builder.setView(dialog);
EditText naame = findViewById(R.id.name);
EditText rollno = findViewById(R.id.roll);
EditText cla = findViewById(R.id.clas);
EditText date = findViewById(R.id.dob);
EditText teacher = findViewById(R.id.teacher);
Button up = findViewById(R.id.update);
builder.setTitle("Updating" + " " + name + " " + "record");
builder.show();
up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String n = naame.getText().toString();
String r = rollno.getText().toString();
String c = cla.getText().toString();
String d = date.getText().toString();
String t = teacher.getText().toString();
updatestudents(id,n,r,d,c,t);
Toast.makeText(MainActivity.this,"record updated",Toast.LENGTH_LONG).show();
}
});
}```
In the findViewById() you should add dialog.findViewById()
public void showupdatedialogue(String id , String name){
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = getLayoutInflater();
View dialog = inflater.inflate(R.layout.update,null);
builder.setView(dialog);
EditText naame = dialog.findViewById(R.id.name);
EditText rollno = dialog.findViewById(R.id.roll);
EditText cla = dialog.findViewById(R.id.clas);
EditText date = dialog.findViewById(R.id.dob);
EditText teacher = dialog.findViewById(R.id.teacher);
Button up = dialog.findViewById(R.id.update);
builder.setTitle("Updating" + " " + name + " " + "record");
builder.show();
up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String n = naame.getText().toString();
String r = rollno.getText().toString();
String c = cla.getText().toString();
String d = date.getText().toString();
String t = teacher.getText().toString();
updatestudents(id,n,r,d,c,t);
Toast.makeText(MainActivity.this,"record updated",Toast.LENGTH_LONG).show();
}
});
}
Related
SQlite Data is not updating into listview. no error showing just not save the edited value. when I click the list view it will open with the inserted value to edit but when I push the update button it won't update. Any Solution for my Problem ??
ListDataActivity.java
listView = findViewById(R.id.listViewId);
loadData();
}
public void loadData() {
//Create an arraylist so that i can load the data to add in the arraylist
ArrayList<String> listData = new ArrayList<>();
Cursor cursor = databaseHelper.showAllData();
//jodi kono cursor e row na thake
if (cursor.getCount() == 0) {
Toast.makeText(getApplicationContext(), "no data is available", Toast.LENGTH_LONG).show();
} else {
while (cursor.moveToNext()) {
listData.add(cursor.getString(1) + " \t " + cursor.getString(2));
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.textViewId, listData);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
String selectedValue = adapterView.getItemAtPosition(position).toString();
cursor.moveToPosition(position);
String name = cursor.getString(1);
String surName = cursor.getString(2);
// listData.add(cursor.getString(1) + " \t " + cursor.getString(2));
Intent intent = new Intent(ListDataActivity.this, UpdateActivity.class);
Toast.makeText(getApplicationContext(), "Selected Value : " + selectedValue, Toast.LENGTH_LONG).show();
intent.putExtra("id", id);
intent.putExtra("name", name);
intent.putExtra("surName", surName);
startActivity(intent);
finish();
}
});
UpdateActivity.java
id = getIntent().getExtras().getLong("id");
String name = getIntent().getExtras().getString("name");
String surName = getIntent().getExtras().getString("surName");
updateName.setText(name);
updatePhone.setText(surName);
updateButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
String name = updateName.getText().toString();
String surName = updatePhone.getText().toString();
if(view.getId()==R.id.updatebuttonId){
ListDataActivity.databaseHelper.updateInformation(id,name,surName);
startActivity(new Intent(UpdateActivity.this,ListDataActivity.class));
finish();
}
}
});
DatabaseHelper.Java
public int updateInformation(long id, String name, String surName) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(NAME,name);
contentValues.put(SURNAME,surName);
String whereArgs[] = {""+id};
int count = sqLiteDatabase.update(TABLE_NAME,contentValues,NAME+ "=?",whereArgs);
return count;
}
I believe that your issue is that you are trying to update using a WHERE clause that is effectively saying update the row where the NAME = the id that has been passed (likely to never find such a row).
You need to change the 3rd parameter passed to the update method to be the name of the id column. So you want something like :-
int count = sqLiteDatabase.update(TABLE_NAME,contentValues,ID+ "=?",whereArgs); //<<<<< ID instead of NAME
Note the above assumes that the String Constant ID contains the name of the id column. So you may have to change ID accordingly.
I'm trying to make a program in android studio that when sellected a higher education it automatically adds 200$ to the pay that was previously entered. But instead of getting 500+200=700, I get 500200. I ran trough the code numerous times and just can't seem to find the error. I'm still new on Java. This is the second window that appears when submitting the information, It shows all the info entered in the first window, but for some reason it can't 200 to the entered pay
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rezultatas);
Intent duom = getIntent();
String pavarde = duom.getStringExtra("pavarde");
String issilavinimas = duom.getStringExtra("issilavinimas");
int pay = duom.getIntExtra("atlyginimas", 0);
String laikas = duom.getStringExtra("laikas");
TextView rez = findViewById(R.id.rezultatas);
rez.setText("Pavardė: "+pavarde+"\n");
rez.append("Išsilavinimas: "+issilavinimas+"\n");
if(issilavinimas.equals("Aukštasis")){
rez.append("Gaunamas atlyginimas: " +pay+ 200 + "\n");
} else{
rez.append("Gaunamas atlyginimas: "+pay+ "\n");
}
rez.append("Keliasi: "+laikas+"\n");
}
This is the first window where all the information is entered:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void saugoti(View v){
EditText txt = findViewById(R.id.lastName);
String pavarde = txt.getText().toString();
Spinner issilavinimas = findViewById(R.id.issilavinimas);
String issilav = issilavinimas.getSelectedItem().toString();
EditText atl = findViewById(R.id.pay);
int pay = Integer.parseInt(atl.getText().toString());
TextView txt2 = findViewById(R.id.time);
String laikas = txt2.getText().toString();
Intent duom = new Intent(this, rezultatas.class);
duom.putExtra("pavarde", pavarde);
duom.putExtra("issilavinimas", issilav);
duom.putExtra("laikas", laikas);
duom.putExtra("atlyginimas", pay);
startActivity(duom);
}
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
Try this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rezultatas);
Intent duom = getIntent();
String pavarde = duom.getStringExtra("pavarde");
String issilavinimas = duom.getStringExtra("issilavinimas");
int pay = duom.getIntExtra("atlyginimas", 0);
int total=pay+ 200;
String laikas = duom.getStringExtra("laikas");
TextView rez = findViewById(R.id.rezultatas);
rez.setText("Pavardė: "+pavarde+"\n");
rez.append("Išsilavinimas: "+issilavinimas+"\n");
if(issilavinimas.equals("Aukštasis")){
rez.append("Gaunamas atlyginimas: " + total + "\n");
} else{
rez.append("Gaunamas atlyginimas: "+pay+ "\n");
}
rez.append("Keliasi: "+laikas+"\n");
}
when you + with String concatination is actually working there instead of addition
This is my source code:
public class ListorderActivity extends AppCompatActivity {
TextView lblTotal;
ListView listView;
MealClass mealDetails;
MealListDataAdapter mealAdapter;
ArrayList<OrderClassDetail> orderlist;
float totalPrice;
private class MealListDataAdapter extends ArrayAdapter<OrderClassDetail> {
int layoutResID;
ArrayList<OrderClassDetail> mealList = new ArrayList<>();
private class ViewHolder {
Button btndelete;
ImageView imgmeal;
TextView lblName;
TextView lblPrice;
TextView lblQuantity;
TextView lblSaltSpicy;
TextView lblSoup;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
String soupStr;
View view = convertView;
if (convertView == null) {
view = ((LayoutInflater) ListorderActivity.this.getSystemService("layout_inflater")).inflate(this.layoutResID, null);
holder = new ViewHolder();
holder.lblName = (TextView) view.findViewById(R.id.txtOrderMealName);
holder.lblPrice = (TextView) view.findViewById(R.id.txtOrderMealPrice);
holder.lblSoup = (TextView) view.findViewById(R.id.txtOrderMealSoup);
holder.lblSaltSpicy = (TextView) view.findViewById(R.id.txtSaltSpicy);
holder.lblQuantity = (TextView) view.findViewById(R.id.txtOrderMealQuantity);
holder.imgmeal = (ImageView) view.findViewById(R.id.mealOrder);
holder.btndelete = (Button) view.findViewById(R.id.delete);
view.setTag(holder);
holder.btndelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mealAdapter.remove((OrderClassDetail) ((Button) v).getTag());
mealAdapter.notifyDataSetChanged();
}
});
} else {
holder = (ViewHolder) view.getTag();
}
try {
OrderClassDetail mealObj = (OrderClassDetail) this.mealList.get(position);
int mealOrderNo = mealObj.getMealNo();
String str = BuildConfig.FLAVOR;
if (mealObj.isHaveSoup()) {
soupStr = "with Soup";
} else {
soupStr = "no Soup";
}
holder.lblName.setText(ListorderActivity.this.mealDetails.getMealName(mealOrderNo));
TextView textView = holder.lblPrice;
StringBuilder sb = new StringBuilder();
sb.append("Price/meal: ");
sb.append(ListorderActivity.this.mealDetails.getMealPrice(mealOrderNo));
textView.setText(sb.toString());
TextView textView2 = holder.lblSoup;
StringBuilder sb2 = new StringBuilder();
sb2.append("Adds On: ");
sb2.append(soupStr);
textView2.setText(sb2.toString());
TextView textView3 = holder.lblSaltSpicy;
StringBuilder sb3 = new StringBuilder();
sb3.append("Salt: ");
sb3.append(mealObj.getSaltPercent());
sb3.append("% : Spice: ");
sb3.append(mealObj.getSpicyPercent());
sb3.append("%");
textView3.setText(sb3.toString());
TextView textView4 = holder.lblQuantity;
StringBuilder sb4 = new StringBuilder();
sb4.append("No. of Order(s): ");
sb4.append(mealObj.getOrderQuantity());
textView4.setText(sb4.toString());
holder.imgmeal.setBackgroundResource(ListorderActivity.this.mealDetails.getMealImage(mealOrderNo));
holder.btndelete.setTag(mealObj);
} catch (Exception e) {
e.printStackTrace();
}
return view;
}
public MealListDataAdapter(Context context, int resourceLayoutID,ArrayList<OrderClassDetail> listObj) {
super(context, resourceLayoutID, listObj);
layoutResID = resourceLayoutID;
mealList.addAll(listObj);
}
public void addAll(ArrayList<OrderClassDetail> obj) {
mealList.clear();
mealList.addAll(obj);
}
public void remove(OrderClassDetail object) {
super.remove(object);
mealList.remove(object);
ListorderActivity.this.totalPrice = 0.0f;
Iterator it = this.mealList.iterator();
while (it.hasNext()) {
OrderClassDetail orbobj = (OrderClassDetail) it.next();
int mealOrderNo = orbobj.getMealNo();
int quant = orbobj.getOrderQuantity();
ListorderActivity.this.totalPrice += ListorderActivity.this.mealDetails.getMealPrice(mealOrderNo) * ((float) quant);
TextView textView = ListorderActivity.this.lblTotal;
StringBuilder sb = new StringBuilder();
sb.append("Total Amount: Php ");
sb.append(String.format("%.2f", new Object[]{Float.valueOf(ListorderActivity.this.totalPrice)}));
textView.setText(sb.toString());
}
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listorder_activityy);
mealDetails = new MealClass();
orderlist = (ArrayList) getIntent().getSerializableExtra("oderList");
lblTotal = (TextView) findViewById(R.id.txtTotalPrice);
listView = (ListView) findViewById(R.id.listView);
mealAdapter = new ListorderActivity.MealListDataAdapter(getBaseContext(), R.layout.custom_listview_layout,this.orderlist);
listView.setAdapter(this.mealAdapter);
Iterator it = orderlist.iterator();
while (it.hasNext()) {
OrderClassDetail orbobj = (OrderClassDetail) it.next();
totalPrice += mealDetails.getMealPrice(orbobj.getMealNo()) * ((float) orbobj.getOrderQuantity());
TextView textView = lblTotal;
StringBuilder sb = new StringBuilder();
sb.append("Total Amount: Php ");
sb.append(String.format("%,.2f", new Object[]{Float.valueOf(this.totalPrice)}));
textView.setText(sb.toString());
}
}
My stack trace:
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object[] java.util.Collection.toArray()' on a null object reference
at java.util.ArrayList.addAll(ArrayList.java:188)
at com.example.myhappymeal.ListorderActivity$MealListDataAdapter.<init>(ListorderActivity.java:120)
at com.example.myhappymeal.ListorderActivity.onCreate(ListorderActivity.java:158)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2280)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
at android.app.ActivityThread.access$800(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1305)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5293)
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)
This is the code that I use
dbhelper mydb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
final Intent profile = getIntent();
final String user = profile.getExtras().getString("tete");
final EditText username = (EditText) findViewById(R.id.Pusername);
final EditText password = (EditText) findViewById(R.id.Ppassword);
username.setText(user);
username.setInputType(InputType.TYPE_NULL); //Supaya username tidak dapat diganti
Button update = (Button) findViewById(R.id.btupdate);
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newpassword = password.getText().toString();
String newusername = username.getText().toString();
if (password.getText().toString().trim().length() < 6) {
Toast.makeText(getApplicationContext(), "Password Baru Harus diisi minimal 6 karakter", Toast.LENGTH_SHORT).show();
} else {
mydb.editData(newusername, newpassword);
Toast.makeText(getApplicationContext(), "berhasil!", Toast.LENGTH_SHORT).show();
}
}
});
This is my code for the dbhelper class
public void editData(String username,String password){
SQLiteDatabase db= this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL_1,username);
contentValues.put(COL_2,password);
db.update(TABLE_NAME,contentValues,"USERNAME = ?", new String[]{username});
//String query="UPDATE " + TABLE_NAME + " SET " + COL_2 + " = '" + password + "' Where " + COL_1 + " = '" + username + "'";
//db.execSQL(query);
}
The logcat gave this error
java.lang.NullPointerException: Attempt to invoke virtual method 'void
com.example.charlie.gate.dbhelper.editData(java.lang.String,
java.lang.String)' on a null object reference
I tried to toast the newusername and the newpassword string to test if it were null and the result were both contain the value as intended, but somehow everytime I click the button the app forced close, Please help
You do not initialize mydb correctly so it is null when you try to use it.
Inside onCreate() add this line:
mydb = new dbhelper(this, ...);
usually you pass this and other parameters for this initialization.
Good evening. Or whatever time you're reading this in. In Android Studio when I was developing the first stages of my app I ran into a problem and I can't seem to find the answer. I am trying to use SharedPrefereces to save user input, but when I try to edit the prefereces [editor = SharedPreferences.edit();] it says that edit() is a non-static method and connot be refereced from a static context.
Here is the code.
public class TheButton extends AppCompatActivity {
EditText ed1, ed2, ed3, ed4;
/*EditText nameInput;
EditText ageInput;
EditText occupationInput;
EditText genderInput;
Button startButtonFinish;*/
protected static final String MyPREFERENCES = "";
public static final String nameInput = "";
public static final int ageInput = 0;
public static final String occupationInput = "";
public static final String genderInput = "";
SharedPreferences sharedpreferences;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_the_button);
ed1 = (EditText) findViewById(R.id.nameInput);
ed2 = (EditText) findViewById(R.id.ageInput);
ed3 = (EditText) findViewById(R.id.occupationInput);
ed4 = (EditText) findViewById(R.id.genderInput);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Button startButtonFinish = (Button) findViewById(R.id.startButtonFinish);
startButtonFinish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String nL = ed1.getText().toString();
String oI = ed3.getText().toString();
String gI = ed4.getText().toString();
//Gives me an error on edit() saying that it edit() is a non-static
// class and they cannot be referenced from a static context
editor = SharedPreferences.edit();
editor.putString(nameInput,nL);
editor.putString(occupationInput, oI);
editor.putString(genderInput, gI);
editor.commit();
startActivity(new Intent(TheButton.this, thebutton2.class));
}
});
}
I will appreciate any help. Thank you!
Instead of this line editor = SharedPreferences.edit();
you should call edit method by sharedpreferences object which is initialized in your code.
You should call the .edit() method by creating object of SharedPreferences. Change SharedPreferences in line, from editor = SharedPreferences.edit(); to editor = sharedPreferences.edit();
EditText ed1, ed2, ed3, ed4;
/*EditText nameInput;
EditText ageInput;
EditText occupationInput;
EditText genderInput;
Button startButtonFinish;*/
protected static final String MyPREFERENCES = "";
public static final String nameInput = "";
public static final int ageInput = 0;
public static final String occupationInput = "";
public static final String genderInput = "";
SharedPreferences sharedpreferences;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_the_button);
ed1 = (EditText) findViewById(R.id.nameInput);
ed2 = (EditText) findViewById(R.id.ageInput);
ed3 = (EditText) findViewById(R.id.occupationInput);
ed4 = (EditText) findViewById(R.id.genderInput);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Button startButtonFinish = (Button) findViewById(R.id.startButtonFinish);
startButtonFinish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String nL = ed1.getText().toString();
String oI = ed3.getText().toString();
String gI = ed4.getText().toString();
//Gives me an error on edit() saying that it edit() is a non-static
// class and they cannot be referenced from a static context
editor = sharedPreferences.edit();
editor.putString(nameInput,nL);
editor.putString(occupationInput, oI);
editor.putString(genderInput, gI);
editor.commit();
startActivity(new Intent(TheButton.this, thebutton2.class));
}
});
}