Cannot read EditText in fragment class - android

I have two tabs and each tab is a Fragment. In one of the fragments (Afragment.claas) I have a dialog box to insert some data, and I want to save them in a database. When I fill the text fields and press OK, the application stops.
I think when I initialize the edittext there is something wrong.
name = (EditText) activity.findViewById(R.id.etProviderName);
The above statement is returning null
Here is my code:
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListFragment;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class Afragment extends ListFragment {
DBAdapter db;
Activity activity;
private static final String fields[] = { "provider._providerName", "_providerMobile" };
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initAdapter();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_add:
add();
return (true);
case R.id.menu_reset:
initAdapter();
return (true);
case R.id.menu_info:
Toast.makeText(activity, "Developed By Omar Al-Shammary", Toast.LENGTH_LONG)
.show();
return (true);
}
return (super.onOptionsItemSelected(item));
}
private void add() {
// TODO Auto-generated method stub
System.out.println("insider Add Method");
final View addView = activity.getLayoutInflater().inflate(R.layout.add_provider, null);
new AlertDialog.Builder(activity).setTitle("Add a Provider").setView(addView)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
System.out.println("Befor calling insert in providers");
insertInProviders();
System.out.println("after calling insert in providers");
}
}).setNegativeButton("Cancel", null).show();
initAdapter();
}
private void initAdapter() {
activity = getActivity();
db = new DBAdapter(activity);
fillTheList();
}
public void fillTheList()
{
db.open();
Cursor data = db.getAllProviders();
CursorAdapter dataSource = new SimpleCursorAdapter(activity,
R.layout.row, data, fields,
new int[] { R.id.first, R.id.last });
setListAdapter(dataSource);
db.close();
setListAdapter(dataSource);
}
public void insertInProviders()
{
EditText name,location,number;
name = (EditText) activity.findViewById(R.id.etProviderName);
location = (EditText) activity.findViewById(R.id.etProviderName);
number = (EditText) activity.findViewById(R.id.etProviderName);
if(name == null)
System.out.println("EditeText name is null");
String provName = name.getText().toString();
if(location == null)
System.out.println("location is null");
String provLocation = location.getText().toString();
String provNumber = number.getText().toString();
System.out.println("Before Open");
db.open();
System.out.println("Before DB.Insert");
db.insertProvider(provName, provLocation, provNumber);
System.out.println("Before Close");
db.close();
}
}
add_provider.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/tvProviderName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name" />
<EditText
android:id="#+id/etProviderName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/tvProvLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Location" />
<EditText
android:id="#+id/etProvLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" />
<TextView
android:id="#+id/tvProvNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Number" />
<EditText
android:id="#+id/etProvNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" />
</LinearLayout>

This is the code I use for declaring buttons in Fragments - maybe it can help you.
What I would do is access the inflated layout and then you should be able to access items underneath it. Let me know if that makes sense.
LinearLayout theLayout = (LinearLayout)inflater.inflate(R.layout.tab_frag1_layout, container, false);
// Register for the Button.OnClick event
Button b = (Button)theLayout.findViewById(R.id.frag1_button);
#Override
public void onClick(View v) {
Toast.makeText(Tab1Fragment.this.getActivity(), "OnClickMe button clicked", Toast.LENGTH_LONG).show();
}
});
return theLayout;
So maybe you should try this since you inflate your View as "addView"
name = (EditText) addView.findViewById(R.id.etProviderName);

The findViewById should not be called by the activity but by the enclosing view. You should have something like:
In the class
View aView;
In the method:
LayoutInflater inflater = getActivity().getLayoutInflater();
aView = inflater.inflate(R.layout.add_provider, null);
...
EditText name = (EditText) aView.findViewById(R.id.etProviderName);
I hope it helps.

Related

Delete selected item in listview and sqllite database and modify the selected item

My app gets name and address and type (sitdown,take away,phone order) of a restaurant and adds it to a sqlite and then to a listview.
I'm trying to have a delete option when one of the items of the listview get long pressed but I don't know how can I do it and I wanted to have edit option after the row item is generated so I create a context menu for long press and a remove and edit option and if the user selects the edit option a dialog pops up and there is edit texts and radiogroup so the user can modify the selected item
I'm new to android.
MainActivity:
package com.test.fastfoodfinder;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private ListView listview;
private Button btn;
Cursor model = null;
RestaurantAdapter adapter = null;
EditText ffname = null;
EditText ffaddress = null;
RadioGroup types = null;
RestaurantHelper helper = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.btn);
helper = new RestaurantHelper(this);
ffname = findViewById(R.id.edittext_name);
ffaddress = findViewById(R.id.edittext_name);
types = findViewById(R.id.radiogroup_type);
listview = findViewById(R.id.list_view);
model = helper.getAll();
startManagingCursor(model);
adapter = new RestaurantAdapter(model);
listview.setAdapter(adapter);
btn.setOnClickListener(onSave);
registerForContextMenu(listview);
}
public void onDestroy() {
super.onDestroy();
helper.close();
}
boolean doubleBackToExitPressedOnce = false;
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, (ContextMenu.ContextMenuInfo) menuInfo);
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
menu.add(0, 1, 0, "Edit");
menu.add(0, 2, 1, "Remove");
menu.add(0, 3, 2, "Add Note");
menu.add(0, 4, 3, "All Notes");
}
public boolean onContextItemSelected(MenuItem item) {
if (item.getTitle().equals("Edit")) {
TextView title = new TextView(this);
title.setText("Edit Your Inputs");
title.setBackgroundColor(Color.DKGRAY);
title.setPadding(10, 16, 10, 10);
title.setGravity(Gravity.CENTER);
title.setTextColor(Color.WHITE);
title.setTextSize(20);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View loginForm = inflater.inflate(R.layout.set_dialog, null, false);
builder.setView(loginForm);
builder.setCustomTitle(title);
AlertDialog dialog = builder.create();
dialog.getWindow().getAttributes().windowAnimations = R.style.customdialog;
dialog.show();
} else if (item.getTitle().equals("Remove")) {
} else if (item.getTitle().equals("Add Note")) {
} else if (item.getTitle().equals("All Notes")) {
}
return super.onContextItemSelected(item);
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
ListView listView = findViewById(R.id.list_view);
EditText nameInput = findViewById(R.id.edittext_name);
EditText addressInput = findViewById(R.id.editText_address);
RadioGroup types = findViewById(R.id.radiogroup_type);
int id = item.getItemId();
switch (id) {
case R.id.clearlist:
helper.deleteDatabase(this);
listView.setAdapter(null);
break;
case R.id.clearforum:
nameInput.setText("");
addressInput.setText("");
types.check(0);
break;
case R.id.settings:
break;
case R.id.exit:
finish();
System.exit(0);
break;
}
return super.onOptionsItemSelected(item);
}
private View.OnClickListener onSave = new View.OnClickListener() {
#Override
public void onClick(View v) {
String type = null;
switch (types.getCheckedRadioButtonId()) {
case R.id.sitdown:
type = ("sitdown");
break;
case R.id.take_away:
type = ("take_away");
break;
case R.id.phone_order:
type = ("phone_order");
break;
}
if (ffname.getText().toString().isEmpty()) {
Toast.makeText(MainActivity.this, "Please enter a name to continue", Toast.LENGTH_SHORT).show();
Animation right = AnimationUtils.loadAnimation(MainActivity.this, R.anim.alert);
ffname.startAnimation(right);
btn.startAnimation(right);
} else if (ffaddress.getText().toString().isEmpty()) {
Toast.makeText(MainActivity.this, "Please enter an address to continue", Toast.LENGTH_SHORT).show();
Animation shake = AnimationUtils.loadAnimation(MainActivity.this, R.anim.alert);
ffaddress.startAnimation(shake);
btn.startAnimation(shake);
} else if (type.equals("")) {
Toast.makeText(MainActivity.this, "Please select a type", Toast.LENGTH_SHORT).show();
Animation shake = AnimationUtils.loadAnimation(MainActivity.this, R.anim.alert);
types.startAnimation(shake);
} else {
helper.insert(ffname.getText().toString(), ffaddress.getText().toString(), type, null);
model.requery();
Toast.makeText(MainActivity.this, "Total number of FastFoods in the list:" + listview.getAdapter().getCount(), Toast.LENGTH_SHORT).show();
}
}
};
class RestaurantAdapter extends CursorAdapter {
RestaurantAdapter(Cursor cursor) {
super(MainActivity.this, cursor);
}
public void bindView(View row, Context context, Cursor cursor) {
RestaurantHolder holder = (RestaurantHolder) row.getTag();
holder.populateFrom(cursor, helper);
}
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.row_layout, parent, false);
Animation animation = AnimationUtils.loadAnimation(MainActivity.this, R.anim.fadein);
row.startAnimation(animation);
RestaurantHolder holder = new RestaurantHolder(row);
row.setTag(holder);
return (row);
}
}
static class RestaurantHolder {
private TextView nameV = null;
private TextView addressV = null;
private ImageView icon = null;
RestaurantHolder(View row) {
nameV = row.findViewById(R.id.listview_name);
addressV = row.findViewById(R.id.listview_address);
icon = row.findViewById(R.id.type_ic);
}
void populateFrom(Cursor cursor, RestaurantHelper helper) {
nameV.setText(helper.getName(cursor));
addressV.setText(helper.getName(cursor));
if (helper.getType(cursor).equals("sitdown")) {
icon.setImageResource(R.drawable.sitdownn);
} else if (helper.getType(cursor).equals("take_away")) {
icon.setImageResource(R.drawable.takeaway);
} else if (helper.getType(cursor).equals("phone_order")) {
icon.setImageResource(R.drawable.phoneorderr);
}
}
}
}
sqlopenhelper
package com.test.fastfoodfinder;
import android.content.Context;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
class RestaurantHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME="lunchlist.db";
private static final int SCHEMA_VERSION=1;
public RestaurantHelper(Context context) {
super(context, DATABASE_NAME, null, SCHEMA_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS restaurants (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, address TEXT, type TEXT, notes TEXT);");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// no-op, since will not be called until 2nd schema
// version exists
}
public Cursor getAll() {
return(getReadableDatabase()
.rawQuery("SELECT _id, name, address, type, notes FROM restaurants ORDER BY name",
null));
}
public void deleteDatabase(Context mContext) {
mContext.deleteDatabase(DATABASE_NAME);
}
public void insert(String name, String address,
String type, String notes) {
ContentValues cv=new ContentValues();
cv.put("name", name);
cv.put("address", address);
cv.put("type", type);
cv.put("notes", notes);
getWritableDatabase().insert("restaurants", "name", cv);
}
public String getName(Cursor c) {
return(c.getString(1));
}
public String getAddress(Cursor c) {
return(c.getString(2));
}
public String getType(Cursor c) {
return(c.getString(3));
}
public String getNotes(Cursor c) {
return(c.getString(4));
}
}
dialog
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"><![CDATA[>
]]>
<TextView
android:id="#+id/address"
style="#style/texts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="48dp"
android:text="Address"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/name" />
<TextView
android:id="#+id/type"
style="#style/texts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="52dp"
android:text="Type"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/address" />
<TextView
android:id="#+id/name"
style="#style/texts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Name"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"></TextView>
<EditText
android:id="#+id/edittext_name"
style="#style/texts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="60dp"
android:layout_marginLeft="60dp"
android:hint="Please enter fast food name"
app:layout_constraintStart_toEndOf="#+id/name"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/editText_address"
style="#style/texts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="46dp"
android:layout_marginLeft="46dp"
android:layout_marginTop="16dp"
android:hint="Please enter fast food address"
app:layout_constraintStart_toEndOf="#+id/address"
app:layout_constraintTop_toBottomOf="#+id/edittext_name" />
<RadioGroup
android:id="#+id/radiogroup_type"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="14dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="#+id/type"
app:layout_constraintTop_toBottomOf="#+id/editText_address">
<RadioButton
android:id="#+id/sitdown"
style="#style/texts"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sit Down" />
<RadioButton
android:id="#+id/take_away"
style="#style/texts"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Take away" />
<RadioButton
android:id="#+id/phone_order"
style="#style/texts"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Phone Order" />
</RadioGroup>
<Button
android:id="#+id/btn"
style="#style/texts"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:paddingTop="16dp"
android:text="Add"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/radiogroup_type" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_begin="0dp" />
<androidx.constraintlayout.widget.Barrier
android:id="#+id/barrier"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:barrierDirection="left" />
</androidx.constraintlayout.widget.ConstraintLayout>
any help would be appreciated
first you should create your method for update and delete in your RestaurantHelper.java.
This example of updating an item.
public boolean UpdateData(String name, String address, String type, String note) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(YOUR_COLUMN_NAME, name);
contentValues.put(YOUR_COLUMN_ADDRESS, address);
contentValues.put(YOUR_COLUMN_TYPE, type);
contentValues.put(YOUR_COLUMN_NOTE, note);
db.update(YOUR_TABLE, contentValues, "name= ? AND address = ?", new String[] { name, address } ); // update the item WHERE name = 'name' and address = 'address'
return true;
}
Then create also the method for deleting.
public Cursor deleteData(String your_uniqure_id) {
SQLiteDatabase db = this.getReadableDatabase();
db.execSQL("DELETE FROM your_table WHERE _id = " + your_uniqure_id);
return null;
}
call this method whenever you want.

Button doesn't respond on anything when pressed

What I'm facing is that whenever I press the button to save data to check if the fields is filled up and if it is then it will pass data to back4app but nothing happens even. The Android monitor/Run doesnt even show that the button is being pressed nor the Logcat.
I have a log in activity, register activity, and the main activity. After Logging in it will take you to the main activity which is empty for now but you need to use the navigation bar to take you to this activity and even the fields are filled or not the button does not respond at all. I put a toast to make sure that the button works but the toast doesnt show.
The code below I just copied in the registration form which is the same concept, fill the form test if theres something in there, if not then message will appear then it will send data to back4app. But the button in this problem doesnt work.
This is the button command
package com.example.back4app.userregistrationexample.Classes;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
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.EditText;
import android.widget.Toast;
import android.view.View.OnClickListener;
import com.example.back4app.userregistrationexample.R;
import com.parse.Parse;
import com.parse.ParseObject;
import com.parse.ParseUser;
public class Purchases extends AppCompatActivity {
private EditText establishmentView;
private EditText particularsView;
private EditText amountView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.app_bar_purchases);
establishmentView = (EditText) findViewById(R.id.Edt_Establishment);
particularsView = (EditText) findViewById(R.id.Edt_Particular);
amountView = (EditText) findViewById(R.id.Edt_purchasesnumber);
final Button save = (Button) findViewById(R.id.btn_purchasessave);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
boolean validationError = false;
StringBuilder validationErrorMessage = new StringBuilder("Please, insert ");
if (isEmpty(establishmentView)) {
validationError = true;
validationErrorMessage.append("an Establisment");
}
if (isEmpty(particularsView)) {
if (validationError) {
validationErrorMessage.append(" and ");
}
validationError = true;
validationErrorMessage.append("a Particular");
}
if (isEmpty(amountView)) {
if (validationError) {
validationErrorMessage.append(" and ");
}
validationError = true;
validationErrorMessage.append("a Amount");
}
validationErrorMessage.append(".");
if (validationError) {
Toast.makeText(Purchases.this, validationErrorMessage.toString(), Toast.LENGTH_LONG).show();
return;
}
final ProgressDialog dlg = new ProgressDialog(Purchases.this);
dlg.setTitle("Please, wait a moment.");
dlg.setMessage("Signing up...");
dlg.show();
Toast.makeText(getApplicationContext(),"Data Saved",Toast.LENGTH_SHORT).show();
}
});
}
private boolean isEmpty(EditText text) {
if (text.getText().toString().trim().length() > 0) {
return false;
} else {
return true;
}
}
private boolean isMatching(EditText text1, EditText text2){
if(text1.getText().toString().equals(text2.getText().toString())){
return true;
}
else{
return false;
}
}
private void alertDisplayer(String title,String message){
AlertDialog.Builder builder = new AlertDialog.Builder(Purchases.this)
.setTitle(title)
.setMessage(message)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Intent intent = new Intent(Purchases.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
ParseUser.logOut();
}
});
AlertDialog ok = builder.create();
ok.show();
}
}
Edit: This is the app_bar_purchases.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:id="#+id/txt_puchasesbal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp"
android:text="Balance" />
<EditText
android:id="#+id/Edt_Establishment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="70dp"
android:ems="10"
android:hint="Establishment"
android:inputType="textPersonName" />
<EditText
android:id="#+id/Edt_Particular"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="130dp"
android:ems="10"
android:hint="Particulars"
android:inputType="textPersonName" />
<EditText
android:id="#+id/Edt_purchasesnumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="197dp"
android:ems="10"
android:hint="Amount"
android:inputType="number" />
<Button
android:id="#+id/btn_purchasessave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="178dp"
android:text="Save" />
</RelativeLayout>
Heres what happen when I try to debug it and put break in boolean same thing happens when I put the break in button save it doesnt show anything on the Debug no errors or anything
EDIT I have pasted the right xml file
EDIT Does having RelativeLayout makes the button not respond?
EDIT I have pasted the whole java class
EDIT I also tried deleting everything else on the onClick except for
Toast.makeText(getApplicationContext(),"Data Saved",Toast.LENGTH_SHORT).show(); just to see if the button itself works but it didn't even show the toast
Please check your button id in xml file it's btn_addbalance
then check your id in java file it's btn_purchasessave
please correct this check below code
your line
final Button save = findViewById(R.id.btn_purchasessave);
replace with
final Button save = findViewById(R.id.btn_addbalance);
it will help to you
I took reference of a SO question,
Try using this :
save.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getBaseContext(), "clicked", Toast.LENGTH_LONG).show();
}
});
And import this
import android.view.View.OnClickListener;
EDIT
Casting most of the android views is reduntant now but it can be the problem, Try to caste the button like this :
final Button save = (Button) findViewById(R.id.btn_purchasessave);
and try your code.
EDIT 2
Try using save.setOnClickListener(this) like this,
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText establishmentView;
private EditText particularsView;
private EditText amountView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
establishmentView = (EditText) findViewById(R.id.Edt_Establishment);
particularsView = (EditText) findViewById(R.id.Edt_Particular);
amountView = (EditText) findViewById(R.id.Edt_purchasesnumber);
final Button save = (Button) findViewById(R.id.btn_purchasessave);
save.setOnClickListener(this);
}
#Override
public void onClick(View v) {
//do things here
}

Clicking on EditText does absolutely nothing and cursor stays at end

How do I get it to open up the keyboard on click and change the cursor position when the user clicks within the text? I'm sure it's something simple, but I've tried setting focusable and focusableInTouchMode to true, enabled, textIsSelectable, and nothing has worked. Have also tried using the following in my code:
InputMethodManager im = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
im.showSoftInput(typeField, 0);
My .xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_chat"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/softGreen"
android:textColor="#color/darkBlue"
android:windowSoftInputMode="stateAlwaysVisible"
tools:context="com.angelwing.buddyup.ChatActivity">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/softBlue"
android:title="Hey"
app:theme="#style/MyTheme"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:ems="10"
android:hint="Sample Text"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#+id/sendButton"
android:layout_toStartOf="#+id/sendButton"
android:paddingLeft="5dp"
android:id="#+id/typeField"/>
<Button
android:layout_width="50dp"
android:layout_height="wrap_content"
android:src="#drawable/edittext_border"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignTop="#+id/typeField"
android:clickable="true"
android:onClick="send"
android:id="#+id/sendButton" />
<ToggleButton
android:textOn="Sun"
android:textOff="Sun"
android:layout_width="#dimen/weekend_toggle_button_width"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
android:id="#+id/sundayButton" />
<ToggleButton
android:textOn="M"
android:textOff="M"
android:layout_width="#dimen/weekday_toggle_button_width"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/sundayButton"
android:layout_toRightOf="#+id/sundayButton"
android:layout_toEndOf="#+id/sundayButton"
android:layout_marginRight="-3dp"
android:layout_marginLeft="-3dp"
android:id="#+id/mondayButton" />
<ToggleButton
android:textOn="T"
android:textOff="T"
android:layout_width="#dimen/weekday_toggle_button_width"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/mondayButton"
android:layout_toRightOf="#+id/mondayButton"
android:layout_toEndOf="#+id/mondayButton"
android:layout_marginRight="-3dp"
android:id="#+id/tuesdayButton" />
<ToggleButton
android:textOn="W"
android:textOff="W"
android:layout_width="#dimen/weekday_toggle_button_width"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/tuesdayButton"
android:layout_toRightOf="#+id/tuesdayButton"
android:layout_toEndOf="#+id/tuesdayButton"
android:layout_marginRight="-3dp"
android:id="#+id/wednesdayButton" />
<ToggleButton
android:textOn="Th"
android:textOff="Th"
android:layout_width="#dimen/weekday_toggle_button_width"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/wednesdayButton"
android:layout_toRightOf="#+id/wednesdayButton"
android:layout_toEndOf="#+id/wednesdayButton"
android:layout_marginRight="-3dp"
android:id="#+id/thursdayButton" />
<ToggleButton
android:textOn="F"
android:textOff="F"
android:layout_width="#dimen/weekday_toggle_button_width"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/thursdayButton"
android:layout_toRightOf="#+id/thursdayButton"
android:layout_toEndOf="#+id/thursdayButton"
android:layout_marginRight="-3dp"
android:id="#+id/fridayButton" />
<ToggleButton
android:textOn="Sat"
android:textOff="Sat"
android:layout_width="#dimen/weekend_toggle_button_width"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/fridayButton"
android:layout_toRightOf="#+id/fridayButton"
android:layout_toEndOf="#+id/fridayButton"
android:layout_marginRight="3dp"
android:id="#+id/saturdayButton" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_below="#+id/sundayButton"
android:layout_above="#+id/edittext"
android:id="#+id/messageListView"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set"
android:textSize="13dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_below="#+id/toolbar"
android:layout_alignBottom="#+id/saturdayButton"
android:layout_toRightOf="#+id/saturdayButton"
android:layout_toEndOf="#+id/saturdayButton"
android:layout_marginLeft="2dp"
android:layout_marginRight="4dp"
android:id="#+id/setButton" />
</RelativeLayout>
My java file:
package com.angelwing.buddyup;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class ChatActivity extends AppCompatActivity {
Toolbar bar;
SharedPreferences sp;
Button sendButton;
EditText typeField;
String otherUserID;
String buddyID;
String buddyName;
String thisUserName;
String thisUserID;
ChatArrayAdapter adapter;
ArrayList<Message> allMessages;
DatabaseReference convoRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
// sendButton = (Button) findViewById(R.id.sendButton);
// typeField = (EditText) findViewById(R.id.typeField);
//
// View view = this.getCurrentFocus();
// if (view != null)
// {
// InputMethodManager im = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
// im.showSoftInputFromInputMethod(view.getWindowToken(), 0);
// }
//
// sp = getSharedPreferences("com.angelwing.buddyup", Context.MODE_PRIVATE);
//
// Bundle buddyInfo = getIntent().getExtras();
//
// otherUserID = buddyInfo.getString("otherUserID");
// buddyID = buddyInfo.getString("buddyID");
// buddyName = buddyInfo.getString("buddyName");
//
// thisUserID = buddyInfo.getString("thisUserID");
// thisUserName = buddyInfo.getString("thisUserName");
//
// bar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(bar);
// getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
// getSupportActionBar().setTitle(buddyName);
// Get allMessages from "Conversations" -> buddyID
// allMessages = new ArrayList<>();
// convoRef = FirebaseDatabase.getInstance().getReference("Conversations").child(buddyID);
//
// ListView messagesList = (ListView) findViewById(R.id.messageListView);
// adapter = new ChatArrayAdapter(getApplicationContext(), allMessages);
// messagesList.setAdapter(adapter);
//
// // Add new messages to allMessages
// convoRef.addChildEventListener(new ChildEventListener() {
// #Override
// public void onChildAdded(DataSnapshot dataSnapshot, String s) {
//
// allMessages.add(dataSnapshot.getValue(Message.class));
// adapter.notifyDataSetChanged();
// }
//
// #Override
// public void onChildChanged(DataSnapshot dataSnapshot, String s) {
//
// }
//
// #Override
// public void onChildRemoved(DataSnapshot dataSnapshot) {
//
// }
//
// #Override
// public void onChildMoved(DataSnapshot dataSnapshot, String s) {
//
// }
//
// #Override
// public void onCancelled(DatabaseError databaseError) {
//
// }
// });
}
public void send(View view)
{
Log.i("Clicked", "Yuppers");
// String chat = typeField.getText().toString();
// chat = truncate(chat);
//
// Message newMessage = new Message(thisUserName, chat, thisUserID);
// convoRef.push().setValue(newMessage);
//
// typeField.setText("");
}
public String truncate (String str)
{
return str;
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.mymenu, menu);
return true;
}
public boolean profileClicked (MenuItem item)
{
Intent intent = new Intent(getApplicationContext(), ProfileScreen.class);
startActivity(intent);
return true;
}
public boolean settingsClicked (MenuItem item)
{
return true;
}
public boolean signOutClicked (MenuItem item)
{
sp.edit().putBoolean("signedIn", false).apply();
// auth.signOut();
Intent intent = new Intent(getApplicationContext(), SignInScreen.class);
startActivity(intent);
return true;
}
}
My activity extends AppCompatActivity, if that's important.
Once I click the back button to make the keyboard disappear, I can't make it reappear when I click inside the EditText. Another thing I can't do is move the cursor when I tap inside a String I've already written so if I messed up somewhere, I have to delete text and retype. It's just so frustrating because I have an EditText in another file that works fine and I didn't have to do anything special. The keyboard is opened when I first enter the activity, which is great.
I'm fairly new to Android development so please put things in simple terms, if possible. Thank you so much!
Try this code it may help you solve your problem...
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
public class AndroidExternalFontsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInputFromInputMethod(view.getWindowToken(), 0);
}
}
}

sqlite database practice in android

I have made an application simple in android for database practice,as i have no idea about Sqlite database I've gone through so many links for it,But most of them are complex,I have created 4 activities 1st (mainActivity) contains 3 Buttons "add","Edit", and "View" in 2nd activity (AddActivity) I have made 3 EditTexts its entered values should be stored in database.So can you please tell me easy steps for doing same?
MainActivity.java
package com.example.db;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button add=(Button)findViewById(R.id.button1);
Button edit=(Button)findViewById(R.id.button2);
Button view=(Button)findViewById(R.id.button3);
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub]
Intent i=new Intent(MainActivity.this,AddActivity.class);
startActivity(i);
}
});
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(MainActivity.this,EditActivity.class);
startActivity(i);
}
});
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(MainActivity.this,ViewActivity.class);
startActivity(i);
}
});
}
}
AddActivity.java
package com.example.db;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class AddActivity extends Activity {
EditText name,addres,phon;
Button ad,cn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
name = (EditText)findViewById(R.id.name);
addres=(EditText)findViewById(R.id.address);
phon = (EditText)findViewById(R.id.phone);
ad =(Button)findViewById(R.id.add);
cn=(Button)findViewById(R.id.cancel);
final SQLiteDatabase db = openOrCreateDatabase("Mydb",MODE_PRIVATE, null);
db.execSQL("create table if not exists simple(name varchar,address varchar,phone varchar");
ad.setOnClickListener(new OnClickListener() {
String n=name.getText().toString();
String a=addres.getText().toString();
String p= phon.getText().toString();
#Override
public void onClick(View v) {
db.execSQL("insert into simple values('n','a','p')");
Cursor c =db.rawQuery("select * from simple",null);
c.moveToFirst();
}
});
cn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i =new Intent(AddActivity.this,MainActivity.class);
startActivity(i);
}
});
}
}
main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="100dp"
android:layout_marginTop="92dp"
android:text="Add" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/button1"
android:layout_below="#+id/button1"
android:layout_marginTop="28dp"
android:text="Edit" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/button2"
android:layout_below="#+id/button2"
android:layout_marginTop="37dp"
android:text="View" />
</RelativeLayout>
Add.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".AddActivity" >
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView2"
android:layout_marginTop="60dp"
android:text="phone"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView3"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="17dp"
android:layout_marginTop="14dp"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView1"
android:layout_alignBottom="#+id/textView1"
android:layout_alignParentRight="true"
android:ems="10" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="80dp"
android:layout_toLeftOf="#+id/editText2"
android:text="Address"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/textView2"
android:ems="10"
android:inputType="textPostalAddress" />
<EditText
android:id="#+id/phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView3"
android:layout_alignParentRight="true"
android:ems="10"
android:inputType="phone" />
<Button
android:id="#+id/add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/phone"
android:layout_marginTop="62dp"
android:layout_toRightOf="#+id/textView1"
android:text="Add" />
<Button
android:id="#+id/cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/add"
android:layout_marginLeft="36dp"
android:layout_toRightOf="#+id/add"
android:text="Cancel" />
</RelativeLayout>
ok I think you want to add the value of edit text into your db
package com.example.databasesample;
import java.util.ArrayList;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity implements OnClickListener {
static EditText edtAdd;
Button btnAdd, btnShow;
ListView listName;
static DataBaseSqlLiteHelper mBaseSqlLiteHelper;
DBModel mDbModel;
ArrayList<DBModel> mArrayList;
ListAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize();
mArrayList = new ArrayList<DBModel>();
mBaseSqlLiteHelper = new DataBaseSqlLiteHelper(MainActivity.this);
mBaseSqlLiteHelper.getReadableDatabase();
mBaseSqlLiteHelper.getWritableDatabase();
}
public void initialize() {
edtAdd = (EditText) findViewById(R.id.edtEnterName);
btnAdd = (Button) findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(this);
btnShow = (Button) findViewById(R.id.btnShow);
btnShow.setOnClickListener(this);
listName = (ListView) findViewById(R.id.listName);
listName.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
deleteItem(mArrayList.get(arg2).getId());
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btnAdd:
addName(edtAdd.getText().toString());
break;
case R.id.btnShow:
showNames();
break;
default:
break;
}
}
// for adding values
public void addName(String name) {
SQLiteDatabase mOpenHelper = mBaseSqlLiteHelper.getWritableDatabase();
ContentValues mContentValues = new ContentValues();
mContentValues.put("name", name);
mOpenHelper.insert("NAMES", null, mContentValues);
mOpenHelper.close();
}
//showing values in list
public void showNames() {
String selectQuery = "SELECT * FROM NAMES";
SQLiteDatabase mDatabase = mBaseSqlLiteHelper.getWritableDatabase();
Cursor mCursor = mDatabase.rawQuery(selectQuery, null);
if (mCursor.moveToFirst()) {
do {
mDbModel = new DBModel();
mDbModel.setId(mCursor.getString(0));
mDbModel.setName(mCursor.getString(1));
mArrayList.add(mDbModel);
} while (mCursor.moveToNext());
}
mAdapter = new ListAdapter(MainActivity.this, mArrayList);
listName.setAdapter(mAdapter);
}
deleteing values
public void deleteItem(String id) {
SQLiteDatabase mDatabase = mBaseSqlLiteHelper.getWritableDatabase();
String delete = "Delete from NAMES Where _id =" + id;
mDatabase.execSQL(delete);
mDatabase.close();
mAdapter.notifyDataSetChanged();
mArrayList.remove(id);
}
//updating item
public static void updateItem(String id) {
SQLiteDatabase mDatabase = mBaseSqlLiteHelper.getWritableDatabase();
String update = "Update NAMES set name=\""
+ edtAdd.getText().toString() + "\" where _id=" + id;
mDatabase.execSQL(update);
mDatabase.close();
}
}
package com.example.databasesample;
public class DatabaseConstants {
public static final String CREATE_TABLE_PROFILE_QUERY = "CREATE TABLE NAMES("
+ " _id integer primary key autoincrement," + " name VARCHAR"
+ ")";
}
package com.example.databasesample;
import android.content.Context;
android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseSqlLiteHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "My Sample DataBase";
private static final int DATABASE_VERSION = 1;
public DataBaseSqlLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DatabaseConstants.CREATE_TABLE_PROFILE_QUERY);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
package com.example.databasesample;
public class DBModel {
String id;
String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.example.databasesample;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
public class ListAdapter extends BaseAdapter {
Context mContext;
ArrayList<DBModel> mArrayList;
public ListAdapter(Context mContext, ArrayList<DBModel> models) {
// TODO Auto-generated constructor stub
this.mArrayList = models;
this.mContext = mContext;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mArrayList.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
LayoutInflater mLayoutInflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mLayoutInflater.inflate(R.layout.list_layout, parent,
false);
TextView txtId = (TextView) convertView.findViewById(R.id.txtId);
txtId.setText(mArrayList.get(position).getId());
TextView txtName = (TextView) convertView
.findViewById(R.id.txtName);
txtName.setText(mArrayList.get(position).getName());
Button btnUpdate=(Button)convertView.findViewById(R.id.btnUpdate);
btnUpdate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
MainActivity.updateItem(mArrayList.get(position).getId());
}
});
}
return convertView;
}
}
//activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<EditText
android:id="#+id/edtEnterName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Enter Name" />
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/edtEnterName"
android:text="Add to Database" />
<Button
android:id="#+id/btnShow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/btnAdd"
android:text="Show" />
<ListView
android:id="#+id/listName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/btnShow" >
</ListView>
//listlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/txtId"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_toRightOf="#+id/txtId" />
<Button
android:id="#+id/btnUpdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtName"
android:text="Update" />
Here I make an app in which you can add ,edit and update your database.i use Two main classes First DataBaseSqlLiteHelper.java to create databse and DatabaseConstants.java to create table. To delete item from db click on list and for update first enter value in edit text.comment on this if you need further help.
Ok if you want only a single value to show on database then you can do like this
take a textView
TextView txtName;
initialize it in my above method of initialize();
then make a method to get single value
// Getting single Name to textView
public void getContact(String id) {
SQLiteDatabase db = mBaseSqlLiteHelper.getReadableDatabase();
String select="Select name from NAMES Where _id ="+id;
Cursor mCursor=db.rawQuery(select,null);
if (mCursor!=null) {
mCursor.moveToFirst();
String name=mCursor.getString(0);
txtName.setText(name);
}
db.close();
}
then call this method on the click of some button and pass the id of the row you want to select.

codes in onClickListener can't be executed

I'm experiencing problem with the following code, I created two buttons with onClickListener added.
It works fine for the Button -- btnAbout, I'm trying to use another way to handle btnIntro, instead of by using findViewById(...) method, but the statement will not be executed when I click btnIntro.
Why does this happen?
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class TestActivity extends Activity {
private final String TAG = "tag";
private Button btnIntro;
private Button btnAbout;
private View layoutView;
private ViewWrapper wrapper;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnAbout = (Button) findViewById(R.id.btnAbout);
if (btnIntro == null) {
LayoutInflater inflator = getLayoutInflater();
layoutView = inflator.inflate(R.layout.main, null, false);
wrapper = new ViewWrapper(layoutView);
layoutView.setTag(wrapper);
} else {
wrapper = (ViewWrapper) layoutView.getTag();
}
btnIntro = wrapper.getButton();
Log.e(TAG, Integer.toHexString(layoutView.getId()) + "");
Log.e(TAG, btnIntro.getText().toString());
btnIntro.setOnClickListener(new OnClickListener() {
{
Log.e(TAG, "static");
}
#Override
public void onClick(View arg0) {
Log.e(TAG, "btnIntro clicked");
Toast.makeText(TestActivity.this, "btnIntro", Toast.LENGTH_SHORT)
.show();
}
});
btnAbout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Log.e(TAG, "btnAbout clicked");
Toast.makeText(TestActivity.this, "about", Toast.LENGTH_SHORT).show();
}
});
}
class ViewWrapper {
View base;
Button btn1;
ViewWrapper(View base) {
this.base = base;
}
Button getButton() {
if (btn1 == null) {
btn1 = (Button) base.findViewById(R.id.btnIntro);
Log.e(TAG, btn1.getText().toString());
}
return btn1;
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/MAIN_LAYOUT_XML"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="30dip">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Test" />
<Button
android:id="#+id/btnIntro"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="btnIntro" />
<Button
android:id="#+id/btnAbout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="btnAbout" />
</LinearLayout>
Problem is that you use to different content views to obtain buttons, one is created when you invoke setContentView() and second you create by invoking inflator.infate(). Thus buttons you get are placed in different content views (only one of which is shown - that created by setContentView). Try that instead:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater inflator = getLayoutInflater();
layoutView = inflator.inflate(R.layout.main, null, false);
setContentView(layoutView);
//..anything you need..
}

Categories

Resources