I created a custom ListView with Custom list view adapter. I want to set current time in every list item in the list. Items in the list box must update the current time every second.
MainActivity.java
package com.example.examapp;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import com.example.exambp.*;
import android.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.LabeledIntent;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
ListView lv;
Activity act=this;
List<ListViewItem> items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
items=new ArrayList<ListViewItem>();
lv=(ListView)findViewById(R.id.listView1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
public void showData(View v)
{
IntentIntegrator i=new IntentIntegrator(this);
i.initiateScan();
}
String[] onedata;
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult != null) {
String x=scanResult.getContents();
EditText et=(EditText)findViewById(R.id.editText1);
et.setText(x);
addToList(x);
}
}
ListViewItem li;
CustomListViewAdapter adapter;
public void addToList(String str)
{
onedata=str.split("/");
li=new ListViewItem();
li.enrollId="EnrollmentID: "+onedata[0].toString();
li.ExamId="ExamID: "+onedata[1].toString();
li.UserId="UserId: "+onedata[2].toString();
li.StartedTime=onedata[3].toString();
li.Duration=onedata[4].toString();
li.AvailableTime="jiukjh";
items.add(li);
adapter=new CustomListViewAdapter(this, items);
lv.setAdapter(adapter);
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_marginLeft="60dp"
android:ems="10"
android:inputType="text" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:onClick="showData"
android:text="#string/btn_val" />
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:orientation="vertical" >
</LinearLayout>
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textView9"
android:layout_toRightOf="#+id/linearLayout2" >
</ListView>
<TextView
android:id="#+id/textView9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/button1"
android:text="Started Exams"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
item_row.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/txtAvailability"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="TextView"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/txtEnrollmentId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/txtAvailability"
android:text="TextView" />
<TextView
android:id="#+id/txtUserId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/txtEnrollmentId"
android:layout_alignBottom="#+id/txtEnrollmentId"
android:layout_marginLeft="78dp"
android:layout_toRightOf="#+id/txtAvailability"
android:text="TextView" />
<TextView
android:id="#+id/txtExamId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/txtEnrollmentId"
android:text="TextView" />
<TextView
android:id="#+id/txtStartTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/txtExamId"
android:layout_alignBottom="#+id/txtExamId"
android:layout_alignLeft="#+id/txtUserId"
android:text="TextView" />
</RelativeLayout>
CustomListViewAdapter.java
package com.example.examapp;
import java.util.Date;
import java.util.List;
import com.example.exambp.*;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class CustomListViewAdapter extends BaseAdapter
{
LayoutInflater inflater;
List<ListViewItem> items;
Activity act;
public CustomListViewAdapter(Activity context, List<ListViewItem> items) {
super();
this.items = items;
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.act=context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
View vi;
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ListViewItem item=items.get(position);
vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.item_row, null);
//ImageView imgThumbnail=(ImageView)vi.findViewById(R.id.imgThumbnail);
TextView txtAvailableTime1=(TextView)vi.findViewById(R.id.txtAvailability);
TextView txtEnrollmentId1=(TextView)vi.findViewById(R.id.txtEnrollmentId);
TextView txtUserId1=(TextView)vi.findViewById(R.id.txtUserId);
TextView txtExamId1=(TextView)vi.findViewById(R.id.txtExamId);
TextView txtStartedTime1=(TextView)vi.findViewById(R.id.txtStartTime);
//imgThumbnail.setImageResource(item.ThumbnailResource);
txtAvailableTime1.setText(item.AvailableTime.toString());
txtEnrollmentId1.setText(item.enrollId.toString());
txtUserId1.setText(item.UserId.toString());
txtExamId1.setText(item.ExamId.toString());
txtStartedTime1.setText(item.StartedTime.toString());
Thread myThread = null;
Runnable runnable = new CountDownRunner();
myThread= new Thread(runnable);
myThread.start();
return vi;
}
public void doWork() {
act.runOnUiThread(new Runnable() {
public void run() {
try{
TextView txtCurrentTime=(TextView)vi.findViewById(R.id.txtAvailability);
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
String curTime = hours + ":" + minutes + ":" + seconds;
txtCurrentTime.setText(curTime);
}catch (Exception e) {
//TextView txtCurrentTime=(TextView)vi.findViewById(R.id.txtAvailability);
//txtCurrentTime.setText(e.getMessage());
}
}
});
}
class CountDownRunner implements Runnable{
// #Override
public void run() {
while(true){
try {
doWork();
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}catch(Exception e){
}
}
}
}
}
This is only run in one time. I want to change current time in List Items continuously.
Every second you will have to loop through each item in your List<ListViewItem> items and then update each item's time. After that call listView.notifyDataSetChanged().
Related
i work about a vtc app and I need to display on the main screen the orders of the client.
I chose the way of customing the list view with an adapter but when i launch the app nothing on the screen except the title of the page.
i divided the adapter code and the fragment code (yeah i work in a fragment) and i want to have your opinion about my code.
Here the Fragment :
package com.cmn.cmnvtc;
import android.Manifest;
import android.app.Dialog;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainPageFragment1 extends Fragment implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
private LinearLayout containerView;
private TextView NoCommand;
private UserLocalStore userLocalStore;
private List<Courses> coursesList;
private ListView lvCourses;
private CoursesAdapter coursesAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_main1, container, false);
userLocalStore = new UserLocalStore(getActivity());
NoCommand = (TextView) v.findViewById(R.id.NoCommand);
lvCourses = (ListView) v.findViewById(R.id.lvCourses);
coursesList = new ArrayList<>();
final Response.Listener<String> responseListener = new Response.Listener<String>(){
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
boolean success = jsonObject.getBoolean("success");
if(success){
int count = jsonObject.getInt("count");
for(int i=0; i<count; i++) {
JSONObject obj = jsonObject.getJSONObject(String.valueOf(i));
String origin = obj.getString("origin");
String destination = obj.getString("destination");
String date_depart = obj.getString("date_depart");
String heure_depart = obj.getString("heure_depart");
int nb_passagers = Integer.parseInt(obj.getString("nb_passagers"));
float prix = Float.parseFloat(obj.getString("prix"));
String mode_paiement = obj.getString("paiement");
String etat_paiement = obj.getString("course_payee");
Courses course = new Courses(origin, destination, date_depart, heure_depart, nb_passagers, prix
, mode_paiement, etat_paiement);
coursesList.add(course);
}
}else{
NoCommand.setEnabled(true);
NoCommand.setText("Oups... Vous n'avez commandé aucune course pour le moment.");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
User currentUser = userLocalStore.getLoggedInUser();
final GetAllCourseRequest getAllCourse = new GetAllCourseRequest(currentUser.user_id,responseListener);
RequestQueue queue = Volley.newRequestQueue(getActivity());
queue.add(getAllCourse);
coursesAdapter = new CoursesAdapter(getActivity(), coursesList);
lvCourses.setAdapter(coursesAdapter);
lvCourses.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getActivity(), "CLicked", Toast.LENGTH_SHORT).show();
}
});
if (googleServicesAvailable()) {
containerView = (LinearLayout) v.findViewById(R.id.containerView);
askForPermission();
}
return v;
}
public boolean googleServicesAvailable() {
GoogleApiAvailability api = GoogleApiAvailability.getInstance();
int isAvaibable = api.isGooglePlayServicesAvailable(getActivity());
if (isAvaibable == ConnectionResult.SUCCESS) {
return true;
} else if (api.isUserResolvableError(isAvaibable)) {
Dialog dialog = api.getErrorDialog(getActivity(), isAvaibable, 0);
dialog.show();
} else {
Toast.makeText(getActivity(), "Can't connect to play services", Toast.LENGTH_SHORT).show();
}
return false;
}
private void explain() {
Snackbar.make(containerView, "Cette permission est nécessaire pour vous géolocalisez", Snackbar.LENGTH_LONG).setAction("Activer", new View.OnClickListener() {
#Override
public void onClick(View view) {
askForPermission();
}
}).show();
}
private void askForPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 2) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(permissions[0]) == false) {
displayOptions();
} else {
explain();
}
}
if (grantResults[1] == PackageManager.PERMISSION_GRANTED) {
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(permissions[1]) == false) {
displayOptions();
} else {
explain();
}
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
private void displayOptions() {
Snackbar.make(containerView, "Vous avez désactivé la permission", Snackbar.LENGTH_LONG).setAction("Paramètres", new View.OnClickListener() {
#Override
public void onClick(View view) {
final Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
final Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null);
intent.setData(uri);
startActivity(intent);
}
}).show();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
My custom adapter :
package com.cmn.cmnvtc;
import android.content.Context;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.List;
/**
* Created by Wild Shadow on 18/06/2017.
*/
public class CoursesAdapter extends BaseAdapter {
private List<Courses> coursesList;
private Context ctx;
public CoursesAdapter(Context context, List<Courses> coursesList) {
this.ctx = context;
this.coursesList = coursesList;
}
#Override
public int getCount() {
return coursesList.size();
}
#Override
public Object getItem(int position) {
return coursesList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = View.inflate(ctx, R.layout.row_courses, null);
TextView adrOrigin = (TextView) v.findViewById(R.id.adrOriginList);
TextView adrDestinaiton = (TextView)
v.findViewById(R.id.adrDestList);
TextView dateDepart = (TextView) v.findViewById(R.id.dateDepList);
TextView heureDepart = (TextView)
v.findViewById(R.id.heureDepList);
ImageButton viewDetails = (ImageButton)
v.findViewById(R.id.viewDetailsCourse);
adrOrigin.setText(coursesList.get(position).getOrigin());
adrDestinaiton.setText(coursesList.get(position).getDestination());
dateDepart.setText(coursesList.get(position).getDate_depart());
heureDepart.setText(coursesList.get(position).getHeure_depart());
return v;
}
}
the model layout :
<?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"
android:padding="6dp">
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_depart_courselist"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/adrOriginList"
android:textSize="17dp"
android:textColor="#000"
android:paddingTop="3dp"
android:text=" : Adresse de départ"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_destination_courselist"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/adrDestList"
android:paddingTop="3dp"
android:textColor="#000"
android:textSize="17dp"
android:text=" : Adresse d'arrivée"
android:layout_marginBottom="5dp"/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_date_depart_courselist"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/dateDepList"
android:paddingTop="3dp"
android:textColor="#000"
android:textSize="17dp"
android:text=" : date de départ"
android:layout_marginBottom="3dp"
android:layout_marginRight="20dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_heure_dep_courselist"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/heureDepList"
android:paddingTop="3dp"
android:textColor="#000"
android:textSize="17dp"
android:text=" : Heure"
android:layout_marginBottom="3dp"/>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_details_courselist"
android:layout_marginLeft="65dp"
android:id="#+id/viewDetailsCourse"
android:paddingTop="5dp"
android:background="?android:selectableItemBackground"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
and the listview :
<ScrollView 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:paddingTop="10dp"
android:theme="#style/AppTheme"
tools:context="com.cmn.cmnvtc.MainPageFragment1">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="center"
android:id="#+id/TitleListCommand"
android:textSize="25dp"
android:layout_marginBottom="15dp"
android:textColor="#727574"
android:text="Liste de mes courses "/>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/TitleListCommand"
android:layout_alignParentStart="true"
android:id="#+id/lvCourses"></ListView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="200dp"
android:textColor="#969696"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:textSize="15dp"
android:textAlignment="center"
android:id="#+id/NoCommand"
android:text=""
android:enabled="false"/>
</RelativeLayout>
</ScrollView>
I hope you will help me to find the error and if you want more, try to explain me how i can optimize my code. TY
You should call notifyDataSetChanged() in the ResponseListener after filling your list.
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
boolean success = jsonObject.getBoolean("success");
if(success){
int count = jsonObject.getInt("count");
for(int i=0; i<count; i++) {
...
coursesList.add(course);
}
//notify adapter about change in data
coursesAdapter.notifyDataSetChanged();
}else{
NoCommand.setEnabled(true);
NoCommand.setText("Oups... Vous n'avez commandé aucune course pour le moment.");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
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 have a few pages realized with a PagerAdapter and one layout-file in the folder "res/layout" and one layout-file in "res/layout-land". Each Layout has two ImageButtons, where:
imageButton1 in portrait has the same ID as the imageButton1 in landscape.
imageButton2 in portrait has the same ID as the imageButton2 in landscape.
I have assigned an onClickListener to imageButton1 button which:
takes the images from the ImageButtons
rescales the Images to fit/fill the ImageButtons
and reassigns the rescaled pictures to the ImageButtons.
But whenever i change the orientation in my emulator the images/pictures in these buttons get lost, or change to the images specified in the layout-file originally and dont refresh to the pictures i assigned to the buttons programmatically.
PS (for example): i assigned in onCreate a listener to button1 and that listener works for this button both in portrait and also in landscape. So these are not seperated buttons!!!!!!
Question: how can i make it work that the images are not lost when changing orientation?
thx for any help in advance!
here is my code:
layout-portrait file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="#+id/table1"
android:background="#drawable/shape"
android:gravity="center"
>
<!-- Row 1-->
<LinearLayout
android:layout_width="fill_parent"
android:orientation="horizontal"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center">
<LinearLayout
android:id="#+id/layout11"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/shape" >
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/ic_launcher" />
</LinearLayout>
<LinearLayout
android:id="#+id/layout12"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/shape" >
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/ic_launcher" />
</LinearLayout>
</LinearLayout>
layout-landscape file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="#+id/table1"
android:background="#drawable/shape"
android:gravity="center"
>
<LinearLayout
android:layout_width="fill_parent"
android:orientation="horizontal"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center">
<LinearLayout
android:id="#+id/layout11"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/shape" >
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/ic_launcher" />
</LinearLayout>
<LinearLayout
android:id="#+id/layout12"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/shape" >
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/ic_launcher" />
</LinearLayout>
</LinearLayout>
MyPageAdapter-class:
package com.example.Pagercheck;
import java.util.List;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
public class MyPageAdapter extends PagerAdapter
{
List<View> pages = null;
public MyPageAdapter(List<View> pages)
{
this.pages = pages;
}
#Override
public int getCount()
{
return pages.size();
}
#Override
public boolean isViewFromObject(View view, Object object)
{
return view.equals(object);
}
#Override
public Object instantiateItem(View collection, int position)
{
View v = pages.get(position);
((ViewPager) collection).addView(v, 0);
return v;
}
#Override
public void destroyItem(View collection, int position, Object view)
{
((ViewPager) collection).removeView((View) view);
}
#Override
public void finishUpdate(View arg0) {
}
#Override
public void startUpdate(View arg0) {
}
}
My MainActivity-Class:
package com.example.Pagercheck;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.SimpleOnPageChangeListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener
{
private List<View> pages;
private MyPageAdapter pagerAdapter;
private ViewPager viewPager;
private static Context context; //member zum speichern für context für andere Klassen
public static Context getContext(){ return context;} //context für andere Klassen zugänglich machen
//private Button btn1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
context = this; //context in member speichern
LayoutInflater inflater = LayoutInflater.from(this);
pages = new ArrayList<View>();
View page = inflater.inflate(R.layout.page, null);
pages.add(page);
page = inflater.inflate(R.layout.page, null);
pages.add(page);
page = inflater.inflate(R.layout.page, null);
pages.add(page);
page = inflater.inflate(R.layout.page, null);
pages.add(page);
page = inflater.inflate(R.layout.page, null);
pages.add(page);
pagerAdapter = new MyPageAdapter(pages);
viewPager = new ViewPager(this);
viewPager.setAdapter(pagerAdapter);
viewPager.setCurrentItem(0);
setContentView(viewPager);
for (int i_page=0;i_page<pages.size();i_page++)
{
//Drag-Listener auf ImageButtons:
pages.get(i_page).findViewById(R.id.imageButton1).setOnLongClickListener(new MyLongClickListener());
pages.get(i_page).findViewById(R.id.imageButton1).setOnClickListener(this);
pages.get(i_page).findViewById(R.id.imageButton2).setOnLongClickListener(new MyLongClickListener());
//Drag-Listener auf LinearLayouts:
pages.get(i_page).findViewById(R.id.layout11).setOnDragListener(new MyDragListener());
pages.get(i_page).findViewById(R.id.layout12).setOnDragListener(new MyDragListener());
}
super.onCreate(savedInstanceState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onWindowFocusChanged(boolean hasFocus)
{
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
//NOTE FOR STACKOVERFLOW
//I COMMENTED THIS OUT SO THAT MY IMAGE BUTTONS DOESNT GET LOST AFTER PAGE 2 SO THAT I CAN TEST MY APP PROPERLY WITH ONCLICK:
// Bitmap bmp_stift=BitmapFactory.decodeResource(getContext().getResources(), R.drawable.stift);
//
// for (int i_page=0;i_page<pages.size();i_page++)
// {
//
// ((ImageButton)pages.get(i_page).findViewById(R.id.imageButton1)).setImageBitmap(bmp_stift);
// scalePictureToFitButtom((ImageButton)pages.get(i_page).findViewById(R.id.imageButton1));
// scalePictureToFitButtom((ImageButton)pages.get(i_page).findViewById(R.id.imageButton2));
//
//
// }
}
public void scalePictureToFitButtom(ImageButton img_btn)
{
int width=img_btn.getWidth();
int height=img_btn.getHeight();
BitmapDrawable draw=(BitmapDrawable)img_btn.getDrawable();
Bitmap bmp = ((BitmapDrawable)draw).getBitmap();
Bitmap resized = Bitmap.createScaledBitmap(bmp, width-40, height-40, true); //bissle schmaler und niedriger damit man noch den Klickeffekt sieht
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
params.width=width;
params.height=height;
img_btn.setImageBitmap(resized);
img_btn.setLayoutParams(params);
pagerAdapter.notifyDataSetChanged();
}
#Override
public void onClick(View view)
{
Bitmap bmp_stift=BitmapFactory.decodeResource(getContext().getResources(), R.drawable.stift);
for (int i_page=0;i_page<pages.size();i_page++)
{
((ImageButton)pages.get(i_page).findViewById(R.id.imageButton1)).setImageBitmap(bmp_stift);
scalePictureToFitButtom((ImageButton)pages.get(i_page).findViewById(R.id.imageButton1));
scalePictureToFitButtom((ImageButton)pages.get(i_page).findViewById(R.id.imageButton2));
}
Toast einToast = Toast.makeText(view.getContext(), "clicked", Toast.LENGTH_SHORT);
einToast.show();
}
}
UPDATE:
i did it like this now (example for saving and restoring Bitmap of imageButton1):
#Override
protected void onSaveInstanceState(Bundle outState)
{
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
BitmapDrawable draw=(BitmapDrawable)((ImageButton)pages.get(0).findViewById(R.id.imageButton1)).getDrawable();
Bitmap bmp = ((BitmapDrawable)draw).getBitmap();
outState.putParcelable("IMG_OF_BUTTON1", bmp);
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onRestoreInstanceState(savedInstanceState);
Bitmap bmp= savedInstanceState.getParcelable("IMG_OF_BUTTON1");
((ImageButton)pages.get(0).findViewById(R.id.imageButton1)).setImageBitmap(bmp);
}
i have a few pages realized with a PagerAdapter and within that some LinearLayouts, which have some ImageButtons.
My Issue:
i want to get the imagebuttons from all the layouts from my pages on app-start, get the size of them and to resize the images to fill the imagebuttons. Gettting the images and rescaling them works fine, BUT if i do this at the function "onWindowFocusChanged" it only works on the first two pages. The ImageButtons on the third page until the last page are just gone. I assume the problem is that either these pages OR the linear-layouts OR the ImageButtons on these pages are not drawn yet so that it doesnt work.
To prove this i assigned a on-click listener to one of these buttons and do my calculation then and not already at onWindowFocusChanged. This has the same effect, BUT if i click the button after i have wiped over all pages it works on all pages.
Question: how can i make it work on startup for all pages OR without having to wipe over all pages first?
thx for any help in advance!
here is my code:
layout-portrait file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="#+id/table1"
android:background="#drawable/shape"
android:gravity="center"
>
<!-- Row 1-->
<LinearLayout
android:layout_width="fill_parent"
android:orientation="horizontal"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center">
<LinearLayout
android:id="#+id/layout11"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/shape" >
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/ic_launcher" />
</LinearLayout>
<LinearLayout
android:id="#+id/layout12"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/shape" >
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/ic_launcher" />
</LinearLayout>
</LinearLayout>
layout-landscape file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="#+id/table1"
android:background="#drawable/shape"
android:gravity="center"
>
<LinearLayout
android:layout_width="fill_parent"
android:orientation="horizontal"
android:layout_height="fill_parent"
android:layout_weight="1"
android:gravity="center">
<LinearLayout
android:id="#+id/layout11"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/shape" >
<ImageButton
android:id="#+id/imageButton1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/ic_launcher" />
</LinearLayout>
<LinearLayout
android:id="#+id/layout12"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:background="#drawable/shape" >
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="#drawable/ic_launcher" />
</LinearLayout>
</LinearLayout>
MyPageAdapter-class:
package com.example.Pagercheck;
import java.util.List;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
public class MyPageAdapter extends PagerAdapter
{
List<View> pages = null;
public MyPageAdapter(List<View> pages)
{
this.pages = pages;
}
#Override
public int getCount()
{
return pages.size();
}
#Override
public boolean isViewFromObject(View view, Object object)
{
return view.equals(object);
}
#Override
public Object instantiateItem(View collection, int position)
{
View v = pages.get(position);
((ViewPager) collection).addView(v, 0);
return v;
}
#Override
public void destroyItem(View collection, int position, Object view)
{
((ViewPager) collection).removeView((View) view);
}
#Override
public void finishUpdate(View arg0) {
}
#Override
public void startUpdate(View arg0) {
}
}
My MainActivity-Class:
package com.example.Pagercheck;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.SimpleOnPageChangeListener;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener
{
private List<View> pages;
private MyPageAdapter pagerAdapter;
private ViewPager viewPager;
private static Context context; //member zum speichern für context für andere Klassen
public static Context getContext(){ return context;} //context für andere Klassen zugänglich machen
//private Button btn1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
context = this; //context in member speichern
LayoutInflater inflater = LayoutInflater.from(this);
pages = new ArrayList<View>();
View page = inflater.inflate(R.layout.page, null);
pages.add(page);
page = inflater.inflate(R.layout.page, null);
pages.add(page);
page = inflater.inflate(R.layout.page, null);
pages.add(page);
page = inflater.inflate(R.layout.page, null);
pages.add(page);
page = inflater.inflate(R.layout.page, null);
pages.add(page);
pagerAdapter = new MyPageAdapter(pages);
viewPager = new ViewPager(this);
viewPager.setAdapter(pagerAdapter);
viewPager.setCurrentItem(0);
setContentView(viewPager);
for (int i_page=0;i_page<pages.size();i_page++)
{
//Drag-Listener auf ImageButtons:
pages.get(i_page).findViewById(R.id.imageButton1).setOnLongClickListener(new MyLongClickListener());
pages.get(i_page).findViewById(R.id.imageButton1).setOnClickListener(this);
pages.get(i_page).findViewById(R.id.imageButton2).setOnLongClickListener(new MyLongClickListener());
//Drag-Listener auf LinearLayouts:
pages.get(i_page).findViewById(R.id.layout11).setOnDragListener(new MyDragListener());
pages.get(i_page).findViewById(R.id.layout12).setOnDragListener(new MyDragListener());
}
super.onCreate(savedInstanceState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onWindowFocusChanged(boolean hasFocus)
{
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
//NOTE FOR STACKOVERFLOW
//I COMMENTED THIS OUT SO THAT MY IMAGE BUTTONS DOESNT GET LOST AFTER PAGE 2 SO THAT I CAN TEST MY APP PROPERLY WITH ONCLICK:
// Bitmap bmp_stift=BitmapFactory.decodeResource(getContext().getResources(), R.drawable.stift);
//
// for (int i_page=0;i_page<pages.size();i_page++)
// {
//
// ((ImageButton)pages.get(i_page).findViewById(R.id.imageButton1)).setImageBitmap(bmp_stift);
// scalePictureToFitButtom((ImageButton)pages.get(i_page).findViewById(R.id.imageButton1));
// scalePictureToFitButtom((ImageButton)pages.get(i_page).findViewById(R.id.imageButton2));
//
//
// }
}
public void scalePictureToFitButtom(ImageButton img_btn)
{
int width=img_btn.getWidth();
int height=img_btn.getHeight();
BitmapDrawable draw=(BitmapDrawable)img_btn.getDrawable();
Bitmap bmp = ((BitmapDrawable)draw).getBitmap();
Bitmap resized = Bitmap.createScaledBitmap(bmp, width-40, height-40, true); //bissle schmaler und niedriger damit man noch den Klickeffekt sieht
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
params.width=width;
params.height=height;
img_btn.setImageBitmap(resized);
img_btn.setLayoutParams(params);
pagerAdapter.notifyDataSetChanged();
}
#Override
public void onClick(View view)
{
Bitmap bmp_stift=BitmapFactory.decodeResource(getContext().getResources(), R.drawable.stift);
for (int i_page=0;i_page<pages.size();i_page++)
{
((ImageButton)pages.get(i_page).findViewById(R.id.imageButton1)).setImageBitmap(bmp_stift);
scalePictureToFitButtom((ImageButton)pages.get(i_page).findViewById(R.id.imageButton1));
scalePictureToFitButtom((ImageButton)pages.get(i_page).findViewById(R.id.imageButton2));
}
Toast einToast = Toast.makeText(view.getContext(), "clicked", Toast.LENGTH_SHORT);
einToast.show();
}
}
I have made an application simple in android for database practice,as i have no idea about Sqlite database I've gone through so many links for it,But most of them are complex,I have created 4 activities 1st (mainActivity) contains 3 Buttons "add","Edit", and "View" in 2nd activity (AddActivity) I have made 3 EditTexts its entered values should be stored in database.So can you please tell me easy steps for doing same?
MainActivity.java
package com.example.db;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button add=(Button)findViewById(R.id.button1);
Button edit=(Button)findViewById(R.id.button2);
Button view=(Button)findViewById(R.id.button3);
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub]
Intent i=new Intent(MainActivity.this,AddActivity.class);
startActivity(i);
}
});
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(MainActivity.this,EditActivity.class);
startActivity(i);
}
});
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(MainActivity.this,ViewActivity.class);
startActivity(i);
}
});
}
}
AddActivity.java
package com.example.db;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class AddActivity extends Activity {
EditText name,addres,phon;
Button ad,cn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
name = (EditText)findViewById(R.id.name);
addres=(EditText)findViewById(R.id.address);
phon = (EditText)findViewById(R.id.phone);
ad =(Button)findViewById(R.id.add);
cn=(Button)findViewById(R.id.cancel);
final SQLiteDatabase db = openOrCreateDatabase("Mydb",MODE_PRIVATE, null);
db.execSQL("create table if not exists simple(name varchar,address varchar,phone varchar");
ad.setOnClickListener(new OnClickListener() {
String n=name.getText().toString();
String a=addres.getText().toString();
String p= phon.getText().toString();
#Override
public void onClick(View v) {
db.execSQL("insert into simple values('n','a','p')");
Cursor c =db.rawQuery("select * from simple",null);
c.moveToFirst();
}
});
cn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i =new Intent(AddActivity.this,MainActivity.class);
startActivity(i);
}
});
}
}
main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="100dp"
android:layout_marginTop="92dp"
android:text="Add" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/button1"
android:layout_below="#+id/button1"
android:layout_marginTop="28dp"
android:text="Edit" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/button2"
android:layout_below="#+id/button2"
android:layout_marginTop="37dp"
android:text="View" />
</RelativeLayout>
Add.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".AddActivity" >
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView2"
android:layout_marginTop="60dp"
android:text="phone"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView3"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="17dp"
android:layout_marginTop="14dp"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView1"
android:layout_alignBottom="#+id/textView1"
android:layout_alignParentRight="true"
android:ems="10" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="80dp"
android:layout_toLeftOf="#+id/editText2"
android:text="Address"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/textView2"
android:ems="10"
android:inputType="textPostalAddress" />
<EditText
android:id="#+id/phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/textView3"
android:layout_alignParentRight="true"
android:ems="10"
android:inputType="phone" />
<Button
android:id="#+id/add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/phone"
android:layout_marginTop="62dp"
android:layout_toRightOf="#+id/textView1"
android:text="Add" />
<Button
android:id="#+id/cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/add"
android:layout_marginLeft="36dp"
android:layout_toRightOf="#+id/add"
android:text="Cancel" />
</RelativeLayout>
ok I think you want to add the value of edit text into your db
package com.example.databasesample;
import java.util.ArrayList;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity implements OnClickListener {
static EditText edtAdd;
Button btnAdd, btnShow;
ListView listName;
static DataBaseSqlLiteHelper mBaseSqlLiteHelper;
DBModel mDbModel;
ArrayList<DBModel> mArrayList;
ListAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize();
mArrayList = new ArrayList<DBModel>();
mBaseSqlLiteHelper = new DataBaseSqlLiteHelper(MainActivity.this);
mBaseSqlLiteHelper.getReadableDatabase();
mBaseSqlLiteHelper.getWritableDatabase();
}
public void initialize() {
edtAdd = (EditText) findViewById(R.id.edtEnterName);
btnAdd = (Button) findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(this);
btnShow = (Button) findViewById(R.id.btnShow);
btnShow.setOnClickListener(this);
listName = (ListView) findViewById(R.id.listName);
listName.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
deleteItem(mArrayList.get(arg2).getId());
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btnAdd:
addName(edtAdd.getText().toString());
break;
case R.id.btnShow:
showNames();
break;
default:
break;
}
}
// for adding values
public void addName(String name) {
SQLiteDatabase mOpenHelper = mBaseSqlLiteHelper.getWritableDatabase();
ContentValues mContentValues = new ContentValues();
mContentValues.put("name", name);
mOpenHelper.insert("NAMES", null, mContentValues);
mOpenHelper.close();
}
//showing values in list
public void showNames() {
String selectQuery = "SELECT * FROM NAMES";
SQLiteDatabase mDatabase = mBaseSqlLiteHelper.getWritableDatabase();
Cursor mCursor = mDatabase.rawQuery(selectQuery, null);
if (mCursor.moveToFirst()) {
do {
mDbModel = new DBModel();
mDbModel.setId(mCursor.getString(0));
mDbModel.setName(mCursor.getString(1));
mArrayList.add(mDbModel);
} while (mCursor.moveToNext());
}
mAdapter = new ListAdapter(MainActivity.this, mArrayList);
listName.setAdapter(mAdapter);
}
deleteing values
public void deleteItem(String id) {
SQLiteDatabase mDatabase = mBaseSqlLiteHelper.getWritableDatabase();
String delete = "Delete from NAMES Where _id =" + id;
mDatabase.execSQL(delete);
mDatabase.close();
mAdapter.notifyDataSetChanged();
mArrayList.remove(id);
}
//updating item
public static void updateItem(String id) {
SQLiteDatabase mDatabase = mBaseSqlLiteHelper.getWritableDatabase();
String update = "Update NAMES set name=\""
+ edtAdd.getText().toString() + "\" where _id=" + id;
mDatabase.execSQL(update);
mDatabase.close();
}
}
package com.example.databasesample;
public class DatabaseConstants {
public static final String CREATE_TABLE_PROFILE_QUERY = "CREATE TABLE NAMES("
+ " _id integer primary key autoincrement," + " name VARCHAR"
+ ")";
}
package com.example.databasesample;
import android.content.Context;
android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseSqlLiteHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "My Sample DataBase";
private static final int DATABASE_VERSION = 1;
public DataBaseSqlLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DatabaseConstants.CREATE_TABLE_PROFILE_QUERY);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
package com.example.databasesample;
public class DBModel {
String id;
String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.example.databasesample;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
public class ListAdapter extends BaseAdapter {
Context mContext;
ArrayList<DBModel> mArrayList;
public ListAdapter(Context mContext, ArrayList<DBModel> models) {
// TODO Auto-generated constructor stub
this.mArrayList = models;
this.mContext = mContext;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mArrayList.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
LayoutInflater mLayoutInflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mLayoutInflater.inflate(R.layout.list_layout, parent,
false);
TextView txtId = (TextView) convertView.findViewById(R.id.txtId);
txtId.setText(mArrayList.get(position).getId());
TextView txtName = (TextView) convertView
.findViewById(R.id.txtName);
txtName.setText(mArrayList.get(position).getName());
Button btnUpdate=(Button)convertView.findViewById(R.id.btnUpdate);
btnUpdate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
MainActivity.updateItem(mArrayList.get(position).getId());
}
});
}
return convertView;
}
}
//activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<EditText
android:id="#+id/edtEnterName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Enter Name" />
<Button
android:id="#+id/btnAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/edtEnterName"
android:text="Add to Database" />
<Button
android:id="#+id/btnShow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/btnAdd"
android:text="Show" />
<ListView
android:id="#+id/listName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/btnShow" >
</ListView>
//listlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/txtId"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_toRightOf="#+id/txtId" />
<Button
android:id="#+id/btnUpdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtName"
android:text="Update" />
Here I make an app in which you can add ,edit and update your database.i use Two main classes First DataBaseSqlLiteHelper.java to create databse and DatabaseConstants.java to create table. To delete item from db click on list and for update first enter value in edit text.comment on this if you need further help.
Ok if you want only a single value to show on database then you can do like this
take a textView
TextView txtName;
initialize it in my above method of initialize();
then make a method to get single value
// Getting single Name to textView
public void getContact(String id) {
SQLiteDatabase db = mBaseSqlLiteHelper.getReadableDatabase();
String select="Select name from NAMES Where _id ="+id;
Cursor mCursor=db.rawQuery(select,null);
if (mCursor!=null) {
mCursor.moveToFirst();
String name=mCursor.getString(0);
txtName.setText(name);
}
db.close();
}
then call this method on the click of some button and pass the id of the row you want to select.