I made a client program on my android and when I receive long messages it doesn't show the whole msg. I have tried to add android:orientation="horizontal" to the XML file but that didn't fix anything.
package com.example.marcus.chatclient1;
import android.app.Activity;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Array;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import static android.R.layout.list_content;
public class chat extends Activity {
Handler hanGET;
String string = "test";
String name;
EditText msgBox;
Button sButton;
ListView lv;
TextView errorT;
ObjectOutputStream o;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
final Button join = (Button) findViewById(R.id.joinButton);
final EditText nameT = (EditText) findViewById(R.id.editTextName);
msgBox = (EditText)findViewById(R.id.msgField);
sButton = (Button)findViewById(R.id.sendButton);
errorT = (TextView) findViewById(R.id.errorText);
lv = (ListView)findViewById(R.id.ChatList);
msgBox.setVisibility(View.INVISIBLE);
sButton.setVisibility(View.INVISIBLE);
lv.setVisibility(View.INVISIBLE);
join.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
name = nameT.getText().toString();
join.setVisibility(View.INVISIBLE);
nameT.setVisibility(View.INVISIBLE);
lv.setVisibility(View.VISIBLE);
msgBox.setVisibility(View.VISIBLE);
sButton.setVisibility(View.VISIBLE);
new Thread(new ClientThread()).start();
final ArrayList<String> ar = new ArrayList<String>();
final ArrayAdapter ad = new ArrayAdapter(getApplicationContext(),android.R.layout.simple_gallery_item, ar);
lv.setBackgroundColor(Color.BLACK);
lv.setAdapter(ad);
hanGET = new Handler(){
public void handleMessage(Message message) {
ar.add(string);
ad.notifyDataSetChanged();
}
};
}
});
}
class ClientThread implements Runnable {
public void run() {
Message message;
Socket s;
try {
s = new Socket("192.168.0.15", 55555);
o = new ObjectOutputStream(s.getOutputStream());
o.writeObject(name);
ObjectInputStream in = new ObjectInputStream(s.getInputStream());
sButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
String m = msgBox.getText().toString();
o.writeObject(m);
} catch (IOException e) {
e.printStackTrace();
}
}
});
while(true) {
try {
string = in.readObject().toString();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
message = Message.obtain();
hanGET.sendMessage(message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<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:orientation="horizontal"
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.marcus.chatclient1.chat">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Join"
android:id="#+id/joinButton"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text="Name"
android:ems="10"
android:id="#+id/editTextName"
android:layout_marginBottom="31dp"
android:layout_above="#+id/joinButton"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/errorText"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/ChatList"
android:layout_alignParentTop="true"
android:clickable="false"
android:layout_alignBottom="#+id/joinButton"
android:choiceMode="none"
tools:listitem="#android:layout/simple_gallery_item"
tools:listfooter="#layout/activity_chat"
android:visibility="visible"
android:layout_centerHorizontal="true"
android:headerDividersEnabled="false" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:ems="10"
android:id="#+id/msgField"
android:layout_below="#+id/ChatList"
android:layout_toRightOf="#+id/errorText"
android:layout_toEndOf="#+id/errorText"
android:visibility="visible" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send"
android:id="#+id/sendButton"
android:layout_alignBottom="#+id/msgField"
android:layout_toRightOf="#+id/joinButton"
android:layout_toEndOf="#+id/joinButton"
android:visibility="visible" />
</RelativeLayout>
A ListView must have the layout_height attribute not setted to wrap_content. A ListView content height is dynamic, since you don't always have the same number of cells. Thus, you need to match the parent size or have a fixed height.
Related
I want to create an activity to search for users by full name. I created everything I needed and it worked properly, except for one thing. When I press search button the result are not show in recyclerview. I need to go back and the the results are shown. I need to do these 2 steps to see the results.
Yes the search bar and view holder are overlap, I will try to fixed later. Do you know how to make it so that once searched the results are displayed immediately without having to go back
This is my layout for view holder
<?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:layout_width="match_parent"
android:layout_height="75dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:id="#+id/parent_layout"
android:background="#drawable/recycler_view_border">
<com.mikhaellopez.circularimageview.CircularImageView
android:id="#+id/imageProfile"
android:layout_width="60dp"
android:layout_height="60dp"
android:tint="#808080"
android:layout_marginStart="10dp"
android:layout_marginTop="7dp"
app:civ_border_color="#color/dark_blue"
app:civ_border_width="2dp"
app:srcCompat="#drawable/defaultimage"/>
<TextView
android:id="#+id/userFullName"
android:layout_toEndOf="#+id/imageProfile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:layout_marginEnd="20dp"
android:layout_marginStart="10dp"
android:gravity="center"
android:text="#string/fullname"
android:textSize="16sp"
android:textColor="#color/black"/>
<com.google.android.material.button.MaterialButton
android:id="#+id/buttonAdd"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginTop="13dp"
android:layout_marginEnd="10dp"
android:layout_marginStart="340dp"
android:background="#drawable/btn_background"
app:cornerRadius="8dp"
android:drawableTop="#drawable/ic_action_add" />
</RelativeLayout>
This is my layout for activity
<?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"
tools:context=".SendFriendRequests">
<LinearLayout
android:id="#+id/linearlayout"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_marginLeft="13dp"
android:orientation="vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<EditText
android:id="#+id/searchUsername"
android:layout_width="318dp"
android:layout_height="45dp"
android:layout_marginTop="20dp"
android:background="#drawable/edt_background"
android:hint="#string/searchFriends"
android:imeOptions="actionNext"
android:importantForAutofill="no"
android:inputType="text"
android:paddingStart="16dp"
android:paddingEnd="16dp" />
<com.google.android.material.button.MaterialButton
android:id="#+id/buttonSearch"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginStart="333dp"
android:layout_marginTop="-47dp"
android:layout_marginEnd="10dp"
android:background="#drawable/btn_background"
android:drawableTop="#drawable/ic_action_search"
app:cornerRadius="8dp" />
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="580dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="#+id/linearlayout"
app:layout_constraintVertical_bias="0.99"
tools:layout_editor_absoluteX="-16dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
This is my adapter
package com.example.chatappjava;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.mikhaellopez.circularimageview.CircularImageView;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
public class SendFriendRequestAdapter extends RecyclerView.Adapter<SendFriendRequestAdapter.ViewHolder> {
private static final String TAG = "ContactsAdapter";
private ArrayList<UserData> arrayListUserData = new ArrayList<>();
private Context context;
public SendFriendRequestAdapter(ArrayList<UserData> arrayListUserData, Context context) {
this.arrayListUserData = arrayListUserData;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_send_friend_request_item, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(ViewHolder holder, #SuppressLint("RecyclerView") int position) {
Log.d(TAG, "onBindViewHolder: called.");
Glide.with(context)
.asBitmap()
.load(arrayListUserData.get(position).image)
.into(holder.userProfileImage);
holder.userFullName.setText(arrayListUserData.get(position).name);
holder.buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Connection conn = DatabaseConnection.createDatabaseConnection();
PreparedStatement st1 = conn.prepareStatement(
" insert into FRIEND_REQUESTS values (?,?,?)");
st1.setString(1, arrayListUserData.get(position).friendId);
st1.setString(2, arrayListUserData.get(position).userId);
st1.setInt(3, 0);
st1.execute();
showToast("Friend request is sended");
Intent intent = new Intent(context, MainActivity.class);
intent.putExtra("IdAccount", arrayListUserData.get(position).userId);
context.startActivity(intent);
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
});
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context.getApplicationContext(), specificchat.class);
intent.putExtra("userId", arrayListUserData.get(position).userId);
intent.putExtra("friendId", arrayListUserData.get(position).friendId);
intent.putExtra("friendName", arrayListUserData.get(position).name);
intent.putExtra("friendImage", arrayListUserData.get(position).image);
context.startActivity(intent);
}
});
}
private void showToast(String message) {
Toast.makeText(context.getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
#Override
public int getItemCount() {
return arrayListUserData.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
CircularImageView userProfileImage;
TextView userFullName;
RelativeLayout parentLayout;
Button buttonAdd;
public ViewHolder(View itemView) {
super(itemView);
userProfileImage = itemView.findViewById(R.id.imageProfile);
userFullName = itemView.findViewById(R.id.userFullName);
parentLayout = itemView.findViewById(R.id.parent_layout);
buttonAdd = itemView.findViewById(R.id.buttonAdd);
}
}
}
And this is my java class which use the adapter
package com.example.chatappjava;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class SendFriendRequests extends AppCompatActivity {
private ArrayList<UserData> arrayListUserData = new ArrayList<>();
private Button searchButton;
private EditText searchUsername;
private String userId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
userId = intent.getStringExtra("IdAccount");
setContentView(R.layout.activity_send_friend_request);
searchButton = findViewById(R.id.buttonSearch);
searchUsername = findViewById(R.id.searchUsername);
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Connection conn = DatabaseConnection.createDatabaseConnection();
Statement statement = conn.createStatement();
ResultSet resultat = statement.executeQuery("select ID, FULLNAME, IMAGE from USERS where ID not in (select FRIEND_ID from FRIENDSLIST where USER_ID = " + userId + ") and FULLNAME like '%" + searchUsername.getText().toString() + "%' and ID not in (select RECEIVER_ID from FRIEND_REQUESTS where SENDER_ID = " + userId + ")");
while (resultat.next()) {
arrayListUserData.add(new UserData(resultat.getString("FULLNAME"), resultat.getString("IMAGE"), resultat.getString("ID"), userId));
}
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
initRecycleView();
}
});
}
private void initRecycleView() {
RecyclerView recyclerView = findViewById(R.id.recyclerView);
SendFriendRequestAdapter adapter = new SendFriendRequestAdapter(arrayListUserData, this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
}
I think it's the RecyclerView in your XML that needs to be adjusted at android:layout_height = "0dp"
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toBottomOf="#+id/linearlayout"/>
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.
I'm new to Android and Rest Template.I have developed a android
screen and display JSON data using Rest Template GET method on my
screen.My next step is to update some fields like edit name and add
missing things and save back to the rest Template.
public class MyPreferences extends AppCompatActivity {
TextView tv;
private Listcp = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_preferences);
Resources resources = getResources();
Log.d("Consumer pojo", "onCreate:");
new HttpRequestTask().execute();
}
private class HttpRequestTask extends AsyncTask<Void, Void, ConsumerProfile>{
#Override
protected ConsumerProfile doInBackground(Void... params) {
try {
final String url = "http://192.168.1.213:9001/consumer/local/"+LoginFragment.CONSUMEROBJECT.getId();
RestTemplate restTemplate = new RestTemplate();
ConsumerProfile cp = restTemplate.getForObject(url, ConsumerProfile.class);
return cp;
}catch (Exception e){
Log.e("MainActivity", e.getMessage(),e );
}
return null;
}
#Override
protected void onPostExecute(ConsumerProfile cp){
super.onPostExecute(cp);
Log.d("cppppppppppppppppppppp", "onPostExecute: " + cp.getId());
TextView fname=(TextView)findViewById(R.id.editfname);
TextView mname=(TextView)findViewById(R.id.editmname);
TextView lname=(TextView)findViewById(R.id.editlname);
TextView nname=(TextView)findViewById(R.id.editnname);
TextView dob=(TextView)findViewById(R.id.editdob);
TextView status=(TextView)findViewById(R.id.editstatus);
TextView homeAddress=(TextView)findViewById(R.id.edithomeAddr);
TextView workAddress=(TextView)findViewById(R.id.editworkAddr);
TextView income=(TextView)findViewById(R.id.editincome);
fname.setText(cp.getFirstName());
mname.setText(cp.getMiddleName());
lname.setText(cp.getLastName());
nname.setText(cp.getNickName());
dob.setText(cp.getDob());
status.setText(cp.getStatus());
homeAddress.setText(cp.getHomeAddress());
workAddress.setText(cp.getWorkAddress());
income.setText(cp.getIncome());
}
}This Screen is for Get Method
This is what I did Up to Now.
This code is for Get method.
It'll display The screen like in image.
<?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:orientation="vertical"><![CDATA[
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
]]>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/scrollView2" >
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"> <TextView
android:layout_width="wrap_content"
android:scrollbars="vertical"
android:layout_height="wrap_content"
android:text="firstName"/>
<EditText
android:id="#+id/editfname"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="middleName"/>
<EditText
android:id="#+id/editmname"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="lastName"/>
<EditText
android:id="#+id/editlname"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="nickName"/>
<EditText
android:id="#+id/editnname"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="dob"/>
<EditText
android:id="#+id/editdob"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="status"/>
<EditText
android:id="#+id/editstatus"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="homeAddress"/>
<EditText
android:id="#+id/edithomeAddr"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="workAddress"/>
<EditText
android:id="#+id/editworkAddr"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="income"/>
<EditText
android:id="#+id/editincome"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:scrollbars="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Update Preferences"
android:id="#+id/button"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</ScrollView>
</LinearLayout>
This is my layout.
Actually what I'm trying to do is Get User Information and Edit Information and save back to the same end point.
When the user select Update button Then it I'll Display the Updated Screen.
Any help Appreciated.
Anyone Provide code for that.
Thankful to them.
package com.nusecond.suredeal.app.suredeal.activity;
import android.content.Intent;
import android.content.res.Resources;
import android.net.http.HttpResponseCache;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.nusecond.suredeal.app.R;
import com.nusecond.suredeal.app.suredeal.pojo.Consumer;
import com.nusecond.suredeal.app.suredeal.pojo.ConsumerProfile;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
public class MyPreferences extends AppCompatActivity {
Button button;
TextView tv;
TextView fname,mname,lname,nname,dob,status,homeAddress,workAddress,income;
private String FName,MName,LName,NName,Dob,Status,HomeAddress,WorkAddress,Income;
private List<ConsumerProfile>cp = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_preferences);
Resources resources = getResources();
Log.d("Consumer pojo", "onCreate:");
new HttpRequestTask().execute();
addListenerOnButton();
}
private void addListenerOnButton() {
//final String url = "http://192.168.1.213:9001/consumer/local/"+LoginFragment.CONSUMEROBJECT.getId();
Button button=(Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FName=fname.getText().toString();
MName=mname.getText().toString();
LName=lname.getText().toString();
NName=nname.getText().toString();
Dob=dob.getText().toString();
Status=status.getText().toString();
HomeAddress=homeAddress.getText().toString();
WorkAddress=workAddress.getText().toString();
new HttpUpdateTask().execute();
// Toast.makeText(addListenerOnButton(),"UpdatedSuccessfully",Toast.LENGTH_LONG).show();
Intent intent=new Intent(MyPreferences.this,MainActivity.class);
startActivity(intent);
}
});
}
private class HttpRequestTask extends AsyncTask<Void, Void, ConsumerProfile>{
#Override
protected ConsumerProfile doInBackground(Void... params) {
try {
final String url = "http://192.168.1.213:9001/consumer/local/"+LoginFragment.CONSUMEROBJECT.getId();
RestTemplate restTemplate = new RestTemplate();
ConsumerProfile cp = restTemplate.getForObject(url, ConsumerProfile.class);
return cp;
}catch (Exception e){
Log.e("MainActivity", e.getMessage(),e );
}
return null;
}
#Override
protected void onPostExecute(ConsumerProfile cp){
super.onPostExecute(cp);
Log.d("cppppppppppppppppppppp", "onPostExecute: " + cp.getId());
fname=(TextView)findViewById(R.id.editfname);
mname=(TextView)findViewById(R.id.editmname);
lname=(TextView)findViewById(R.id.editlname);
nname=(TextView)findViewById(R.id.editnname);
dob=(TextView)findViewById(R.id.editdob);
status=(TextView)findViewById(R.id.editstatus);
homeAddress=(TextView)findViewById(R.id.edithomeAddr);
workAddress=(TextView)findViewById(R.id.editworkAddr);
income=(TextView)findViewById(R.id.editincome);
fname.setText(cp.getFirstName());
mname.setText(cp.getMiddleName());
lname.setText(cp.getLastName());
nname.setText(cp.getNickName());
dob.setText(cp.getDob());
status.setText(cp.getStatus());
homeAddress.setText(cp.getHomeAddress());
workAddress.setText(cp.getWorkAddress());
income.setText(cp.getIncome());
//FName=fname.getText().toString();
}
}
private class HttpUpdateTask extends AsyncTask<Void,Void,ConsumerProfile>{
#Override
protected ConsumerProfile doInBackground(Void... params) {
try {
final String url = "http://192.168.1.213:9001/consumer/local/" + LoginFragment.CONSUMEROBJECT.getId();
RestTemplate restTemplate = new RestTemplate();
ConsumerProfile consumerProfile = new ConsumerProfile();
// String m=FName;
consumerProfile.setFirstName(FName);
fname=(TextView)findViewById(R.id.editfname);
Log.d(" llllllllllllll", "doInBackground: " + FName);
consumerProfile.setMiddleName(MName);
consumerProfile.setLastName(LName);
consumerProfile.setNickName(NName);
consumerProfile.setDob(Dob);
consumerProfile.setStatus(Status);
consumerProfile.setHomeAddress(HomeAddress);
consumerProfile.setWorkAddress(WorkAddress);
consumerProfile.setDob(Income);
restTemplate.put(url,consumerProfile);
Log.d("ettttttttttttttt", "doInBackground: ");
return consumerProfile;
}catch (Exception e){
Log.e( "consumer", e.getMessage(),e);
}
return null;
}
}
}
I'm trying to call an EditText from one activity to another but when i do my app crashes.
I've tried using the addPreferencesFromResource method using 'import android.preference.PreferenceActivity' and import android.preference.PreferenceFragment' but the 'addPreferencesFromResource' stays red.
How can I make it callable ?
settings_layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:weightSum="1"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_alignParentLeft="true"
android:layout_marginLeft="0dp"
android:layout_alignParentTop="true"
android:layout_marginTop="0dp"
android:id="#+id/linearLayout">
<TextView
android:layout_width="127dp"
android:layout_height="wrap_content"
android:text="website A"
android:id="#+id/textView3"
android:layout_weight="0.07"
android:layout_marginTop="115dp"
android:layout_below="#+id/linearLayout"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="back"
android:onClick="showZaire"
android:id="#+id/button5"
android:layout_gravity="center_horizontal"
android:layout_alignParentBottom="true"
android:layout_toRightOf="#+id/textView3"
android:layout_toEndOf="#+id/textView3" />
<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="#+id/webA"
android:layout_alignBottom="#+id/textView3"
android:layout_toRightOf="#+id/textView3"
android:layout_toEndOf="#+id/textView3" />
<TextView
android:layout_width="127dp"
android:layout_height="wrap_content"
android:text="website B"
android:id="#+id/textView2"
android:layout_weight="0.07"
android:layout_below="#+id/textView3"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="34dp" />
<EditText
android:layout_width="200dp"
android:layout_height="wrap_content"
android:id="#+id/webB"
android:layout_alignBottom="#+id/textView2"
android:layout_toRightOf="#+id/textView2"
android:layout_toEndOf="#+id/textView2" />
</LinearLayout
Second Activity
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class secondActivity extends Activity {
EditText webs = (EditText)findViewById(R.id.webA);// this is what im trying to call from settings
String web = webs.getText().toString();
TextView titleText;
String title = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.seccond_layout);
Button button = (Button) findViewById(R.id.refresh);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
restartActivity(seccondActivity.this);
}
});
//initialize variables
titleText = (TextView) findViewById(R.id.titleText);
;
//run on new thread because we cannot do network operation on main thread
new Thread(new Runnable() {
#Override
public void run() {
try {
//get the Document object from the site. Enter the link of site you want to fetch
Document document = Jsoup.connect(web).get(); // this is the website string
//Get the title of blog using title tag
title = document.select("h6").text().toString();
//set the title of text view
//Run this on ui thread because another thread cannot touch the views of main thread
runOnUiThread(new Runnable() {
#Override
public void run() {
//set both the text views
titleText.setText(title);
titleText.setMovementMethod(new ScrollingMovementMethod());
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
public void showZaire(View view) {
String button_test;
button_test = ((Button) view).getText().toString();
if (button_test.equals("Home")) {
Intent intent1 = new Intent(this, MainActivity.class);
startActivity(intent1);
} else if (button_test.equals("Directions")) {
Intent intent = new Intent(this, ThirdActivity.class);
startActivity(intent);
}
}
}
settingsActivity
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.text.Editable;
import android.text.Layout;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
/**
* Created by Shane on 10/01/2016.
*/
public class SettingsActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_layout);}
public void showZaire(View view) {
String button_test;
button_test = ((Button) view).getText().toString();
if (button_test.equals("Back")) {
Intent intent1 = new Intent(this, MainActivity.class);
startActivity(intent1);
} else if (button_test.equals("Help")) {
Intent intent2 = new Intent(this, Help.class);
startActivity(intent2);
}
}
}
I have activities
1> mainactivity
which creates SQLite table and add stores data from edittext to mysql table
2> viewdatabse activity
which retrieves data from SQLite table and displayes in listview.
the problem is The same DATA is shown multiple time.
ex.
if i write something in edittext1 the listview will show only data of edittext1 multiple time.
here is the code of mainactivity
package com.example.androiddatabase;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
EditText name,password,date,other;
Button save,show;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name=(EditText)findViewById(R.id.nametext);
password=(EditText)findViewById(R.id.password);
date=(EditText)findViewById(R.id.time);
other=(EditText)findViewById(R.id.other);
save=(Button)findViewById(R.id.button1);
show=(Button)findViewById(R.id.button2);
save.setOnClickListener(this);
show.setOnClickListener(this);
SQLiteDatabase db=null;
try{
db=openOrCreateDatabase("MyIds",MODE_PRIVATE , null);
db.execSQL("create table if not exists MyInfo(names VARCHAR(30),passwords VARCHAR(10),dates INTEGER,others VARCHAR(500))");
}
catch(Exception e){
Toast.makeText(this, e.getMessage().toString(), Toast.LENGTH_LONG).show();
}
finally{
if(db.isOpen()){
db.close();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v==save)
{
String n= name.getText().toString();
String p= password.getText().toString();
String d= date.getText().toString();
String o =other.getText().toString();
SQLiteDatabase db=null;
try{
db=openOrCreateDatabase("MyIds", MODE_PRIVATE, null);
db.execSQL("insert into MyInfo(names,passwords,dates,others)values('"+n+"','"+p+"','"+d+"','"+o+"')");
}
catch(Exception e)
{
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
finally
{
if(db.isOpen())
{
db.close();
}
}
}
else if (v==show)
{
Intent i = new Intent(this, viewdatabse.class);
startActivity(i);
}
}
}
here is the another activity which represens the listview which show data from mysql
package com.example.androiddatabase;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class viewdatabse extends Activity{
ListView lv;
ArrayList<HashMap<String, String>> aa;
String name,password,date,other;
HashMap<String, String> hh;
String n,p,d,o;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.listdatabse);
lv=(ListView)findViewById(R.id.listView1);
aa = new ArrayList<HashMap<String,String>>();
SQLiteDatabase db=null;
try{
db=openOrCreateDatabase("MyIds",MODE_PRIVATE , null);
Cursor c = db.rawQuery("select * from MyInfo", null);
while(c.moveToNext())
{
hh= new HashMap<String, String>();
name=c.getString(c.getColumnIndex("names"));
hh.put(n, name);
password=c.getString(c.getColumnIndex("passwords"));
hh.put(p, password);
date=c.getString(c.getColumnIndex("dates"));
hh.put(d, date);
other=c.getString(c.getColumnIndex("others"));
hh.put(o, other);
aa.add(hh);
}
}
catch(Exception e){
Toast.makeText(this, e.getMessage().toString(), Toast.LENGTH_LONG).show();
}
finally{
if(db.isOpen()){
db.close();
}
}
String s[]={n,p,d,o};
int i[]={R.id.textView1,R.id.textView2,R.id.textView3,R.id.textView4};
SimpleAdapter sa = new SimpleAdapter(this, aa, R.layout.customlist, s, i);
lv.setAdapter(sa);
}
}
here is the mainactivity xml file which has 4 edittext to take user input
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/nametext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName">
<requestFocus />
</EditText>
<EditText
android:id="#+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPassword" />
<EditText
android:id="#+id/time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="time" />
<EditText
android:id="#+id/other"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="save" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="show" />
</LinearLayout>
here is xml for view database activity which has listview to show data.
<?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" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
here is the xml to create custom listview which is directly used in simpleadapter
<?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/textView1"
android:textSize="30dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="#+id/textView2"
android:textSize="30dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>