android.widget.TextView cannot be cast to android.widget.EditView - android

when i tried to run this code it is showing error. what is the problem. please tell me if u find.
But i did not cast Textview to EditText but it showing error.
My xml file:
<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="com.example.dailyexpenses.LoginTypeConfirmation" >
<TextView
android:id="#+id/Confirmation_password_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Confirmation_password"
android:layout_alignParentTop="true"
android:layout_marginTop="38dp"
android:text="#string/loginType_confirm" />
<EditText
android:id="#+id/Confirmation_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/Confirmation_password_info"
android:layout_centerHorizontal="true"
android:layout_marginTop="44dp"
android:ems="10"
android:hint="#string/confirm_password"
android:inputType="textPassword" />
<Button
android:id="#+id/Confirmation_password_submit"
android:layout_width="match_parent"
android:layout_height="35dp"
android:layout_alignLeft="#+id/Confirmation_password"
android:layout_below="#+id/Confirmation_password"
android:layout_marginTop="34dp"
android:background="#color/project_theme"
android:text="#string/submit"
android:textColor="#color/font_color" />
My Java code:
import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.InputType;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginTypeConfirmation extends ActionBarActivity {
private TextView info;
private EditText old_password;
private Button save;
private SQLiteDatabase db;
String login_type = null, password = null, pin_password = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_type_confirmation_ui);
db = openOrCreateDatabase("DailyExpenses", Context.MODE_PRIVATE, null);
info = (TextView) findViewById(R.id.Confirmation_password_info);
old_password = (EditText) findViewById(R.id.Confirmation_password);
save = (Button) findViewById(R.id.Confirmation_password_submit);
checkLoginType();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login_type_confirmation, menu);
return true;
}
public void checkLoginType()
{
Cursor c = db.rawQuery("select login_type password, pin_password from user_information", null);
while(c.moveToNext())
{
login_type = c.getString(0);
password = c.getString(1);
pin_password = c.getString(2);
}
if (login_type.equals("pin_password"))
{
info.setText("Enter your old pin");
old_password.setText("Confirm Pin");
old_password.setInputType(InputType.TYPE_NUMBER_VARIATION_PASSWORD);
}
}
public void validatePassword(View view)
{
if (old_password.getText().toString().equals(password))
{
Intent loginType = new Intent(this, LoginType.class);
startActivity(loginType);
}
else
{
Toast.makeText(this, "Incorrect Password", Toast.LENGTH_SHORT).show();
}
}
}
if i remove checkLoginType() method it's working fine.
thanks in advance.

You need to pass View to your checkLoginType() method, it will look like below code:
public void checkLoginType(View v)
{
Cursor c = db.rawQuery("select login_type password, pin_password from user_information", null);
while(c.moveToNext())
{
login_type = c.getString(0);
password = c.getString(1);
pin_password = c.getString(2);
}
if(login_type.equals("pin_password"))
{
info.setText("Enter your old pin");
old_password.setText("Confirm Pin");
old_password.setInputType(InputType.TYPE_NUMBER_VARIATION_PASSWORD);
}
}
Let me know if you still facing issue...

Just Change public void checkLoginType() to public void checkLoginType(View v)

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.

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);
}
}
}

How to Fetch Record From SQLite in Android

I am not good at Android, learning things. I'm trying to fetch record from SQLite in Android. Here is my code. Please help where is my fault. Thanks.
//DatabaseAdapter.java//
package com.example.wg_an;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class DatabaseAdapter {
SQLiteDatabase database;
DatabaseOpenHelper dbHelper;
public DatabaseAdapter(Context context) {
dbHelper = new DatabaseOpenHelper(context);
}
public void open() {
database = dbHelper.getWritableDatabase();
}
public void close() {
database.close();
}
public long insertTest(String no, String name) {
ContentValues values = new ContentValues();
values.put("no", no);
values.put("name", name);
return database.insert("test", null, values);
}
public ArrayList<String> getAllLabels() {
Cursor mcursor = database.rawQuery("SELECT name FROM "
+ DatabaseOpenHelper.TABLE_NAME, null);
ArrayList<String> result = new ArrayList<String>();
do {
result.add(mcursor.getString(mcursor.getColumnIndex("name")));
} while (mcursor.moveToNext());
return result;
}
}
//MainActivity2.java//
package com.example.wg_an;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity2 extends Activity implements OnClickListener {
EditText etno, etname;
Button btnSave;
DatabaseAdapter dbAdapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
dbAdapter = new DatabaseAdapter(getApplicationContext());
etno = (EditText) findViewById(R.id.txtNo);
etname = (EditText) findViewById(R.id.txtName);
btnSave = (Button) findViewById(R.id.Save);
btnSave.setOnClickListener(this);
Button back = (Button) findViewById(R.id.buttonBackPg);
back.setOnClickListener(this);
Button view_list = (Button) findViewById(R.id.view_list);
view_list.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.buttonBackPg) {
startActivity(new Intent(getApplicationContext(),
MainActivity.class));
}
if (v.getId() == R.id.view_list) {
ListView listview = (ListView) findViewById(R.id.list_all);
ArrayList<String> data = dbAdapter.getAllLabels();
dbAdapter.close();
listview.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, data));
}
if (v.getId() == R.id.Save) {
String no = etno.getText().toString();
String name = etname.getText().toString();
dbAdapter.open();
long inserted = dbAdapter.insertTest(no, name);
if (inserted >= 0) {
Toast.makeText(getApplicationContext(), "data saved",
Toast.LENGTH_LONG).show();
etno.setText("");
etname.setText("");
} else {
Toast.makeText(getApplicationContext(), "data not saved",
Toast.LENGTH_LONG).show();
}
dbAdapter.close();
}
}
}
//activity_main2.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=".MainActivity2" >
<EditText
android:id="#+id/txtNo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="19dp"
android:ems="10"
android:hint="No"
android:inputType="text" >
<requestFocus />
</EditText>
<Button
android:id="#+id/buttonBackPg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Save"
android:layout_alignParentBottom="true"
android:layout_marginBottom="77dp"
android:text="Back" />
<Button
android:id="#+id/Save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/buttonBackPg"
android:layout_centerHorizontal="true"
android:layout_marginBottom="32dp"
android:onClick="onClick"
android:text="Save" />
<EditText
android:id="#+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/textView1"
android:layout_below="#+id/txtNo"
android:layout_marginTop="36dp"
android:ems="10"
android:hint="Name"
android:inputType="text">
</EditText>
<Button
android:id="#+id/view_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtName"
android:layout_below="#+id/Save"
android:text="View List" />
<ListView
android:id="#+id/list_all"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/msg"
android:layout_alignLeft="#+id/msg" >
</ListView>
</RelativeLayout>
Try this edit
public ArrayList<String> getAllLabels() {
Cursor mcursor = database.rawQuery("SELECT name FROM "
+ DatabaseOpenHelper.TABLE_NAME, null);
ArrayList<String> result = new ArrayList<String>();
if(mcursor!=null)
{
//move cursor to first result record
mcursor.moveToFirst();
do {
result.add(mcursor.getString(mcursor.getColumnIndex("name")));
} while (mcursor.moveToNext());
}
return result;
}
for fetch data use like that
public Cursor getdata()
{
Log.v(TAG + ".getdata", "getdatamethod called");
Cursor mCursor = null;
openAsWrite();
mCursor=db.query(tablenam,
new String[] {"column name"},null, null, null, null, null);
return mCursor;
}
Final Working Code is here --
//DatabaseAdapter.java//
package com.example.wg_an;
import java.util.ArrayList;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class DatabaseAdapter {
SQLiteDatabase database;
DatabaseOpenHelper dbHelper;
public DatabaseAdapter(Context context) {
dbHelper = new DatabaseOpenHelper(context);
}
public void open() {
database = dbHelper.getWritableDatabase();
}
public void close() {
database.close();
}
public long insertTest(String no, String name) {
ContentValues values = new ContentValues();
values.put("no", no);
values.put("name", name);
return database.insert("test", null, values);
}
public ArrayList<String> getAllLabels() {
Cursor mcursor = database.rawQuery("SELECT * FROM "
+ DatabaseOpenHelper.TABLE_NAME, null);
ArrayList<String> result = new ArrayList<String>();
if(mcursor!=null)
{
//move cursor to first result record
mcursor.moveToFirst();
do {
String display = mcursor.getString(mcursor.getColumnIndex("name")) + " - " + mcursor.getString(mcursor.getColumnIndex("no"));
result.add(display);
} while (mcursor.moveToNext());
}
return result;
}
}
//MainActivity2.java //
package com.example.wg_an;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity2 extends Activity implements OnClickListener {
EditText etno, etname;
Button btnSave;
DatabaseAdapter dbAdapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
dbAdapter = new DatabaseAdapter(getApplicationContext());
etno = (EditText) findViewById(R.id.txtNo);
etname = (EditText) findViewById(R.id.txtName);
btnSave = (Button) findViewById(R.id.Save);
btnSave.setOnClickListener(this);
Button back = (Button) findViewById(R.id.buttonBackPg);
back.setOnClickListener(this);
Button view_list = (Button) findViewById(R.id.view_list);
view_list.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.buttonBackPg) {
startActivity(new Intent(getApplicationContext(),
MainActivity.class));
}
if (v.getId() == R.id.view_list) {
startActivity(new Intent(getApplicationContext(),
MainActivity3.class));
}
if (v.getId() == R.id.Save) {
String no = etno.getText().toString();
String name = etname.getText().toString();
dbAdapter.open();
long inserted = dbAdapter.insertTest(no, name);
if (inserted >= 0) {
Toast.makeText(getApplicationContext(), "data saved",
Toast.LENGTH_LONG).show();
etno.setText("");
etname.setText("");
} else {
Toast.makeText(getApplicationContext(), "data not saved",
Toast.LENGTH_LONG).show();
}
dbAdapter.close();
}
}
}
//MainActivity3.java//
package com.example.wg_an;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity3 extends Activity implements OnClickListener {
/** Called when the activity is first created. */
DatabaseAdapter dbAdapter;
ListView listview;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
dbAdapter = new DatabaseAdapter(this);
dbAdapter.open();
try {
Button back = (Button) findViewById(R.id.back_2);
back.setOnClickListener(this);
listview = (ListView) findViewById(R.id.list_all);
Log.d("Reading: ", "Reading MA3..");
ArrayList<String> data = dbAdapter.getAllLabels();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, data);
listview.setAdapter(adapter);
dbAdapter.close();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG)
.show();
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.back_2) {
startActivity(new Intent(getApplicationContext(),
MainActivity2.class));
}
}
}
//DatabaseOpenHelper.java//
package com.example.wg_an;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseOpenHelper extends SQLiteOpenHelper {
public static final String DBName = "test_database.db";
public static final String TABLE_NAME = "test";
public static final String TABLE_SQL = "Create Table "+ TABLE_NAME
+"(_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+"no TEXT, "
+"name TEXT);";
public DatabaseOpenHelper(Context context) {
super(context, DBName, null, 1);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase database) {
// TODO Auto-generated method stub
database.execSQL(TABLE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
}
//activity_main2.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=".MainActivity2" >
<Button
android:id="#+id/buttonBackPg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/Save"
android:layout_alignParentBottom="true"
android:layout_marginBottom="77dp"
android:text="Back Screen-1" />
<Button
android:id="#+id/Save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/buttonBackPg"
android:layout_alignLeft="#+id/txtName"
android:onClick="onClick"
android:text="Save" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="16dp"
android:layout_marginTop="21dp"
android:text="Add Records - Screen-2" />
<EditText
android:id="#+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/Save"
android:layout_alignLeft="#+id/txtNo"
android:layout_marginBottom="58dp"
android:ems="10"
android:hint="Name"
android:inputType="text" />
<EditText
android:id="#+id/txtNo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp"
android:ems="10"
android:hint="No"
android:inputType="text" />
<Button
android:id="#+id/view_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/txtName"
android:layout_below="#+id/txtName"
android:text="View List" />
</RelativeLayout>
//activity_main3.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=".MainActivity3" >
<Button
android:id="#+id/back_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="17dp"
android:text="Back Screen-2" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="80dp"
android:text="List of Records - Screen-3" />
<ListView
android:id="#+id/list_all"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="58dp"
android:layout_marginTop="58dp"
android:layout_below="#+id/textView3"
android:layout_centerHorizontal="true" >
</ListView>
</RelativeLayout>

trouble opening xml page

I created two java class and two xml pages . I am trying to when onclick button of one class,open another class. afer opening , memo.xml page showing blank.
see following code.
please help me
My login.java page:
package quesansw.the1;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Login extends Activity{
SQLiteDatabase db;
int z,i=0;
String[] arr = new String[3];
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = openOrCreateDatabase("mydatabase.db",
SQLiteDatabase.CREATE_IF_NECESSARY, null);
final Dialog d1 = new Dialog(this);
Window window = d1.getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
d1.setTitle("Login");
d1.setContentView(R.layout.login);
d1.show();
Button registerques1 = (Button) d1.findViewById(R.id.registerques1);
EditText ques = (EditText) d1.findViewById(R.id.question);
Cursor cur= db.rawQuery("select * from questions1",null);
cur.moveToNext();
System.out.println(cur.getString(0));
System.out.println(cur.getString(1));
ques.append(cur.getString(0));
Cursor c = db.rawQuery("SELECT * from questions1", null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String firstName = c.getString(c.getColumnIndex("question"));
String Name = c.getString(c.getColumnIndex("answer"));
arr[i]=firstName;
i++;
}while (c.moveToNext());
}
}
for(z=0;z<2;z++)
{
registerques1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
if(z == 2)
{
Cursor cur= db.rawQuery("select * from questions1",null);
cur.moveToNext();
EditText ques = (EditText) d1.findViewById(R.id.question);
EditText ans = (EditText) d1.findViewById(R.id.answer);
Editable newTxt=(Editable)ans.getText();
String str = newTxt.toString();
int l=str.length();
int l1=cur.getString(1).length();
int l2=l-l1;
ques.setText(arr[0]);
ans.setText("");
if(l2 == 0)
{
z=5;
}
}
if(z == 5)
{
EditText ques = (EditText) d1.findViewById(R.id.question);
ques.setText(arr[1]);
Cursor cur= db.rawQuery("select * from questions1 where question='"+arr[1]+"' ",null);
cur.moveToNext();
//ques.setText();
EditText ans = (EditText) d1.findViewById(R.id.answer);
System.out.println("------"+ans.getText());
Editable newTxt=(Editable)ans.getText();
String str = newTxt.toString();
int l=str.length();
int l1=cur.getString(1).length();
int l2=l-l1;
ques.setText(arr[1]);
ans.setText("");
/*ques.setText(arr[2]);
ans.setText("");*/
if(l2 == 0)
{
/*Intent intent = new Intent(getBaseContext(), Memo.class);
startActivity(intent);*/
z=6;
}
}
if(z == 6)
{
EditText ques = (EditText) d1.findViewById(R.id.question);
ques.setText(arr[2]);
Cursor cur= db.rawQuery("select * from questions1 where question='"+arr[2]+"' ",null);
cur.moveToNext();
EditText ans = (EditText) d1.findViewById(R.id.answer);
System.out.println("------"+ans.getText());
Editable newTxt=(Editable)ans.getText();
String str = newTxt.toString();
int l=str.length();
int l1=cur.getString(1).length();
//System.out.println(l+l1);
int l2=l-l1;
ques.setText(arr[2]);
ans.setText("");
if(l2 == 0)
{
System.out.println("memo-----");
Intent intent = new Intent(getBaseContext(), Memo.class);
startActivity(intent);
}
}
}
});
}
}
}
login.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="match_parent">
<TextView android:text="Question1" android:id="#+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
<EditText android:id="#+id/question" android:layout_width="match_parent" android:layout_height="wrap_content" android:text=""></EditText>
<EditText android:id="#+id/answer" android:layout_width="match_parent" android:layout_height="wrap_content" android:text=""></EditText>
<Button android:id="#+id/registerques1" android:layout_width="wrap_content" android:text="registerques" android:layout_height="wrap_content"></Button>
</LinearLayout>
Memo.java
package quesansw.the1;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
public class Memo extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Dialog d1 = new Dialog(this);
Window window = d1.getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
d1.setTitle("Register Questions");
d1.setContentView(R.layout.memo);
Button view = (Button) d1.findViewById(R.id.view);
view.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
/*Intent intent = new Intent(getBaseContext(), View.class);
startActivity(intent);*/
}
});
}
}
memo.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="match_parent">
<TextView android:text="Titile" android:id="#+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
<EditText android:id="#+id/question" android:layout_width="match_parent" android:layout_height="wrap_content" android:text=""></EditText>
<TextView android:text="Text" android:id="#+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
<EditText android:minLines="6" android:maxLines="10" android:id="#+id/answer" android:layout_width="match_parent" android:layout_height="wrap_content" android:text=""></EditText>
<TableLayout android:layout_height="wrap_content"
android:layout_width="wrap_content" android:layout_gravity="center"
android:stretchColumns="*">
<TableRow>
<Button android:id="#+id/add" android:layout_width="wrap_content" android:text="ADD" android:layout_height="wrap_content"></Button>
<Button android:id="#+id/view" android:layout_width="wrap_content" android:text="VIEW" android:layout_height="wrap_content"></Button>
</TableRow>
</TableLayout>
</LinearLayout>
You haven't called the show() method for your dialog.
Add d1.show() at the end of your onCreate() method

Cannot read EditText in fragment class

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.

Categories

Resources