trouble opening xml page - android

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

Related

PopUp Window not updating database - Android

I'm trying to create a kind of game using Android Studio. Till now I have done a gridview wich shows players stored in a database. I have had some problems with gridView.setOnItemClickListener, I have had to do it by putting the code into gridView's Adparter.class so if you know how I can do that into gridView's activity please tell me.
My problem now is that when you click on a player a popup window appears in which you could change the player's name or his genre. When you click on Confirm's button the database will automatically been updated, but it doesn't works. I have try to do it step by step by using Toast in order to know if it run that part or not, the problem could be the context, but maybe I'm crazy.
I left you some pics and the code related to it.
Gridview's pic -> http://i.stack.imgur.com/GO4ms.png
PopUp windos's pic -> http://i.stack.imgur.com/aAvcm.png
gridView's adapter class
package es.fingerlabs.gamecohol;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class AdaptadorAmigos extends BaseAdapter {
private Context context;
private ArrayList<Amigo> misAmigos = new ArrayList<Amigo>();
public AdaptadorAmigos(ArrayList<Amigo> list, Context context) {
this.misAmigos = list;
this.context = context;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View gridView = convertView;
if (gridView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
gridView = inflater.inflate(R.layout.item_amigo, null);
}
TextView TextoNombreJugador = (TextView)gridView.findViewById(R.id.tvNombreAmigo);
TextoNombreJugador.setText(misAmigos.get(position).getNombre());
//Handle buttons and add onClickListeners
ImageButton deleteBtn = (ImageButton)gridView.findViewById(R.id.btEliminarAmigo);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something
AmigosSQLiteHelper amigosdbh = new AmigosSQLiteHelper(context, "DBAmigos", null, 1);
SQLiteDatabase db = amigosdbh.getWritableDatabase();
db.delete("Amigos", "id_amigo="+misAmigos.get(position).getId(), null);
misAmigos.remove(position); //or some other task
//Eliminar de la base de datos **************
notifyDataSetChanged();
}
});
// ******* THIS IS WHAT I REFER TO PUT IT ON GRIDVIEW'S ACTIVITY *******
gridView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(context,"Id "+misAmigos.get(position).getId()+" Vidas "+misAmigos.get(position).getVidas(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, VistaAmigo.class);
intent.putExtra("Id", (misAmigos.get(position).getId()));
intent.putExtra("Nombre", (misAmigos.get(position)).getNombre());
intent.putExtra("Genero", (misAmigos.get(position)).getGenero());
context.startActivity(intent);
}
});
return gridView;
}
#Override
public int getCount() {
return misAmigos.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
}
gridView's class
package es.fingerlabs.gamecohol;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class SeleccionarAmigos extends AppCompatActivity {
private ArrayList<Amigo> misAmigos;
private GridView gridView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_amigos);
gridView = (GridView) findViewById(R.id.gvAmigos);
refrescarLista();
/* IF I PUT THAT HERE IT DOES NOTHING
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
Toast.makeText(getApplicationContext(),misAmigos.get(position).getNombre(), Toast.LENGTH_SHORT).show();
}
});*/
/*gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// get the data to pass to the activity based on the position clicked
Intent intent = new Intent(SeleccionarAmigos.this, VistaAmigo.class);
intent.putExtra("Id", (misAmigos.get(position).getId()));
intent.putExtra("Nombre", (misAmigos.get(position)).getNombre());
intent.putExtra("Genero", (misAmigos.get(position)).getGenero());
startActivity(intent);
}
});*/
}
public void obtenerAmigos(){
misAmigos = new ArrayList<Amigo>();
AmigosSQLiteHelper amigosdbh = new AmigosSQLiteHelper(this, "DBAmigos", null, 1);
SQLiteDatabase db = amigosdbh.getReadableDatabase();
Cursor c = db.rawQuery(" SELECT Id_amigo,Nombre,Genero FROM Amigos ", null);
//Nos aseguramos de que existe al menos un registro
if (c.moveToFirst()) {
//Recorremos el cursor hasta que no haya más registros
do {
int id = c.getInt(0);
String nombre= c.getString(1);
String genero= c.getString(2);
Amigo nuevoAmigo = new Amigo(nombre,genero,null);
nuevoAmigo.setId(id);
this.misAmigos.add(nuevoAmigo);
} while(c.moveToNext());
}
db.close();
}
public void refrescarLista(){
obtenerAmigos();
AdaptadorAmigos adapter = new AdaptadorAmigos(misAmigos, this);
gridView.setAdapter(adapter);
}
}
PopUp window class
package es.fingerlabs.gamecohol;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
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.PopupWindow;
import android.widget.Toast;
public class VistaAmigo extends Activity {
private int id;
private String nombre;
private String genero;
private EditText etNombre;
private EditText etGenero;
private Button btConfirmar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vistaamigo);
etNombre = (EditText) findViewById(R.id.etNombreVistaAmigo);
etGenero = (EditText) findViewById(R.id.etGeneroVistaAmigo);
btConfirmar = (Button) findViewById(R.id.btConfirmarAmigo);
Intent i = getIntent();
i.getIntExtra("Id", id);
nombre = i.getStringExtra("Nombre");
genero = i.getStringExtra("Genero");
etNombre.setHint(nombre);
etGenero.setHint(genero);
btConfirmar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AmigosSQLiteHelper amigosdbh = new AmigosSQLiteHelper(VistaAmigo.this, "DBAmigos", null, 1);
SQLiteDatabase db = amigosdbh.getWritableDatabase();
ContentValues valores = new ContentValues();
valores.put("nombre", etNombre.getText().toString());
valores.put("genero", etGenero.getText().toString());
db.update("Amigos", valores, "id_amigo="+id, null);
Toast.makeText(VistaAmigo.this.getBaseContext(),"Nombre: "+etNombre.getText().toString()+" Genero: "+etGenero.getText().toString()+
"Cambios realizados",Toast.LENGTH_LONG);
}
});
}
}
gridView's layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/fondogamecohol">
<GridView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/gvAmigos"
android:layout_gravity="center_horizontal"
android:numColumns="auto_fit"
android:layout_margin="10dp"
android:verticalSpacing="20dp"
android:horizontalSpacing="20dp" />
</LinearLayout>
Gridview's item layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/rounded_corners_white"
android:id="#+id/lyItemAmigo">
<ImageView
android:layout_width="124dp"
android:layout_height="95dp"
android:id="#+id/ivFotoAmigo"
android:background="#d8d8d8"
android:layout_marginTop="10dp"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:clickable="false"
android:src="#drawable/ic_tag_faces_white_36dp" />
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="Chrisitan"
android:id="#+id/tvNombreAmigo"
android:layout_gravity="center"
android:textColor="#333333"
android:textStyle="bold"
android:textSize="18dp"
android:layout_marginTop="5dp"
android:layout_marginRight="12dp"
android:clickable="false"
android:layout_marginLeft="14dp" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:gravity="right"
android:id="#+id/lyBotonesAmigo"
android:layout_marginTop="5dp"
android:layout_marginRight="12dp">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btEditarAmigo"
android:clickable="false"
android:background="#drawable/ic_edit_black_18dp" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btEliminarAmigo"
android:clickable="false"
android:background="#drawable/ic_delete_forever_black_18dp" />
</LinearLayout>
</LinearLayout>
PopUp window layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:theme="#style/PopUp1">
<LinearLayout
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:background="#drawable/rounded_corners_white"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="40dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Modificar amigo"
android:id="#+id/tvModificarAmigo"
android:layout_gravity="center_horizontal"
android:background="#c9ed5a"
android:gravity="center_vertical|center_horizontal"
android:textStyle="bold"
android:textColor="#ffffff" />
<RelativeLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nombre: "
android:id="#+id/tvNombreVistaAmigo"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginStart="28dp"
android:layout_marginTop="51dp"
android:textStyle="bold"
android:textColor="#333333"
android:textSize="20dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/etNombreVistaAmigo"
android:layout_marginStart="10dp"
android:hint="Jugador 1"
android:textColorHint="#333333"
android:textColor="#333333"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_toEndOf="#+id/tvNombreVistaAmigo"
android:layout_toRightOf="#+id/tvNombreVistaAmigo"
android:layout_marginTop="41dp"
android:textSize="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Genero:"
android:id="#+id/tvGeneroVistaAmigo"
android:layout_centerVertical="true"
android:layout_alignStart="#+id/tvNombreVistaAmigo"
android:textColor="#333333"
android:textStyle="bold" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/etGeneroVistaAmigo"
android:hint="Hombre"
android:textColorHint="#333333"
android:textColor="#333333"
android:textStyle="bold"
android:layout_alignStart="#+id/etNombreVistaAmigo"
android:layout_below="#+id/etNombreVistaAmigo"
android:layout_marginTop="23dp"
android:textSize="20dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Confirmar"
android:id="#+id/btConfirmarAmigo"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#drawable/rounded_corners_green"
android:layout_marginBottom="20dp"
android:textStyle="bold"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:textSize="20dp" />
</RelativeLayout>
</LinearLayout>
</RelativeLayout>
From what I´ve seen in your code is, that you try to get the id from an intent in your PopUp window class. You have made one thing wrong:
Intent i = getIntent();
i.getIntExtra("Id", id);
it must be:
Intent i = getIntent();
id = i.getIntExtra("Id", id); //forgott id = here
and you should give a default value to id for example id=-1 . The problem is, by updating your database, you give a non value integer and so it is not possible to update your table.

How can store Data text view data?

In this file i have two Edit text and one textview.I want to sum two number.then result are show in text view.Then i want to store Textview data. please help.i am trying but i am fail.
Activity_main.xml//
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/Edit"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/Edit1"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Add"
android:id="#+id/add"
android:onClick="add"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/sub"
android:id="#+id/sub"
android:onClick="sub"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_gravity="center"
android:paddingBottom="30dp">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/pr"
android:text="Previoues Data"
/>
</LinearLayout>
</LinearLayout>
the java file is
MainActivity.java
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText Edit,Edit1;
Button add, sub, pr;
TextView view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Edit = (EditText) findViewById(R.id.Edit);
Edit1 = (EditText) findViewById(R.id.Edit1);
add = (Button) findViewById(R.id.add);
sub = (Button) findViewById(R.id.sub);
pr = (Button) findViewById(R.id.pr);
view = (TextView) findViewById(R.id.view);
Edit.setText("0");
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int value1 = Integer.parseInt(Edit.getText().toString());
int value2 = Integer.parseInt(Edit1.getText().toString());
int result = value1 + value2;
view.setText(Integer.toString(result));
// Edit.setText(Integer.toString(result));
SharedPreferences sharedPreferences=getSharedPreferences("Mydata",Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putInt("value",result);
editor.commit();
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int value1 = Integer.parseInt(Edit.getText().toString());
int value2 = Integer.parseInt(Edit1.getText().toString());
int result = value1 - value2;
view.setText(Integer.toString(result));
Edit.setText(Integer.toString(result));
}
});
pr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences=getSharedPreferences("Mydata",Context.MODE_PRIVATE);
// int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
String v=sharedPreferences.getInt("value","");
view.setText(v);
}
});
}
}
update your xml file remove onClick from your button
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Add"
android:id="#+id/add"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/sub"
android:id="#+id/sub"
/>
Problem is with your getting value from sharedPreference
String v=sharedPreferences.getInt("value","");
why are you passing string as default value and your
try this String
v = Integer.toString(sharedPreferences.getInt("value",0));
in the layout you´ve got android:onClick="add" there should be a public void add(View v) to handle the event. Do the sum inside that handler.
Please, follow the documentation
http://developer.android.com/reference/android/widget/Button.html and see the :onCLick handling.

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

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)

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>

Android How do display array contents to textview?

How do I loop around contents of an array and display line by line on a text view
java code
package com.stuff;
import android.app.Activity;
import android.os.Bundle;
import android.provider.UserDictionary;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
public class ScrumActivity extends Activity
{
TextView textout;
EditText inputBox;
Button okButton;
ProgressBar progressBar;
Scrumer scrumbler = new Scrumer();
StringBuilder sb = new StringBuilder();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Get elements from XML to use in application
textout = (TextView) findViewById(R.id.textView1);
inputBox = (EditText) findViewById(R.id.inputBox);
okButton = (Button) findViewById(R.id.button1);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
//progressBar.setVisibility(View.VISIBLE);
SpannableStringBuilder sb = new SpannableStringBuilder();
String regularText = "This text is ";
String clickableText = "clickable";
sb.append(regularText);
sb.append(clickableText);
sb.setSpan(new ClickableSpan(), sb.length()-clickableText.length(), sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//tv.setText(sb);
//setting a listener for the button to be clicked
okButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//textout.setText(inputBox.getText().toString());
scrumer.jumble(inputBox.getText().toString());
for(String s : scrumbler.getMatchArray())
sb.append(s+"\n");
textout.setText("ok");
System.out.print(sb.toString());
}
});
}
}
Heres my main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal"
android:orientation="vertical" >
<EditText
android:id="#+id/inputBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Search" />
<TextView
android:id="#+id/textView1"
android:layout_width="184dp"
android:layout_height="wrap_content"/>
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
StringBuilder builder = new StringBuilder();
String[] arr = {"These","are","some","words"};
for (String s : arr){
builder.append(s).append(" ");
textview.setText(builder.toString());
Will put These are some words into your TextView. If you want a line-break after every single string, use builder.append(s).append("\n");

Categories

Resources