Insert sound/audio - java

I have a database containing a ListView and a picture, I want to include in each of each voice data. I've tried but I got a lot of errors. The following are my java and xml.
Database.java
package com.example.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class Database extends SQLiteOpenHelper {
final static String DB_NAME = "db_tum_obat";
public Database(Context context) {
super(context, DB_NAME, null, 1);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE IF NOT EXISTS tum(_id INTEGER PRIMARY KEY AUTOINCREMENT, nama TEXT, nama_latin TEXT, khasiat TEXT, img BLOB, img2 BLOB)";
db.execSQL(sql);
ContentValues values = new ContentValues();
values.put("_id", "1");
values.put("nama", "Jarak Pagar");
values.put("nama_latin", "Jatropha curcas Linn.");
values.put("khasiat",
"ketombe, lemah saraf, menghitamkan rambut, rambut rontok, rematik");
values.put("img", R.drawable.im31);
values.put("img2", R.drawable.home);// im31 nama file gambar dengan
// ukuran 80 x 80 pixel yang ada di
// folder res/drawable pada project
db.insert("tum", "_id", values);
values.put("_id", "2");
values.put("nama", "Kumis Kucing");
values.put("nama_latin", "Orthosipon aristatus (B1) Miq.");
values.put("khasiat",
"ketombe, lemah saraf, menghitamkan rambut, rambut rontok, rematik");
values.put("img", R.drawable.im32);
values.put("img2", R.drawable.keluar1);// im32 nama file gambar dengan
// ukuran 80 x 80 pixel yang ada di
// folder res/drawable pada project
db.insert("tum", "_id", values);
values.put("_id", "3");
values.put("nama", "Lidah Buaya");
values.put("nama_latin", "Aloe Verra Linn.");
values.put("khasiat",
"ketombe, lemah saraf, menghitamkan rambut, rambut rontok, rematik");
values.put("img", R.drawable.im33);
values.put("img2", R.drawable.home);// im33 nama file gambar dengan
// ukuran 80 x 80 pixel yang ada di
// folder res/drawable pada project
db.insert("tum", "_id", values);
values.put("_id", "4");
values.put("nama", "Pandan Wangi");
values.put("nama_latin", "Pandanus amryllifolius Roxb");
values.put("khasiat",
"ketombe, lemah saraf, menghitamkan rambut, rambut rontok, rematik");
values.put("img", R.drawable.im34);
values.put("img2", R.drawable.keluar1);// im34 nama file gambar dengan
// ukuran 80 x 80 pixel yang ada di
// folder res/drawable pada project
db.insert("tum", "_id", values);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS tum");
onCreate(db);
}
}
MainActivity.java
package com.example.database;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity extends Activity {
protected ListView lv;
protected ListAdapter adapter;
SQLiteDatabase db;
Cursor cursor;
EditText et_db;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = (new Database(this)).getWritableDatabase();
lv = (ListView) findViewById(R.id.lv);
et_db = (EditText) findViewById(R.id.et);
try {
cursor = db.rawQuery("SELECT * FROM tum ORDER BY nama ASC", null);
adapter = new SimpleCursorAdapter(this, R.layout.isi_lv, cursor,
new String[] { "nama", "nama_latin", "img" }, new int[] {
R.id.tv_nama, R.id.tv_penyebab, R.id.imV });
lv.setAdapter(adapter);
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
detail(position);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#SuppressWarnings("deprecation")
public void search_db(View v) {
String edit_db = et_db.getText().toString();
if (!edit_db.equals("")) {
try {
cursor = db.rawQuery("SELECT * FROM tum WHERE nama LIKE ?",
new String[] { "%" + edit_db + "%" });
adapter = new SimpleCursorAdapter(this, R.layout.isi_lv,
cursor, new String[] { "nama", "nama_latin", "img" },
new int[] { R.id.tv_nama, R.id.tv_penyebab, R.id.imV });
if (adapter.getCount() == 0) {
Toast.makeText(
this,
"Tidak ditemukan data dengan kata kunci " + edit_db
+ "", Toast.LENGTH_SHORT).show();
} else {
lv.setAdapter(adapter);
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
try {
cursor = db.rawQuery("SELECT * FROM tum ORDER BY nama ASC",
null);
adapter = new SimpleCursorAdapter(this, R.layout.isi_lv,
cursor, new String[] { "nama", "nama_latin", "img" },
new int[] { R.id.tv_nama, R.id.tv_penyebab, R.id.imV });
lv.setAdapter(adapter);
lv.setTextFilterEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void detail(int position) {
int im2 = 0;
String _id = "";
String nama = "";
String latin = "";
String khasiat = "";
if (cursor.moveToFirst()) {
cursor.moveToPosition(position);
im2 = cursor.getInt(cursor.getColumnIndex("img2"));
nama = cursor.getString(cursor.getColumnIndex("nama"));
latin = cursor.getString(cursor.getColumnIndex("nama_latin"));
khasiat = cursor.getString(cursor.getColumnIndex("khasiat"));
}
Intent iIntent = new Intent(this, DetailTum.class);
iIntent.putExtra("dataIM2", im2);
iIntent.putExtra("dataNama", nama);
iIntent.putExtra("dataLatin", latin);
iIntent.putExtra("dataKhasiat", khasiat);
setResult(RESULT_OK, iIntent);
startActivityForResult(iIntent, 99);
}
}
DetailTum.java
package com.example.database;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.TextView;
public class DetailTum extends Activity {
ImageView Im2;
TextView tv_nama, tv_latin, tv_khasiat, id, namaIm;
Gallery gallery;
ImageSwitcher imageSwitcher;
Integer[] imageIDs = new Integer[3];
int msg_im2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail);
Intent iIdentifikasi = getIntent();
msg_im2 = iIdentifikasi.getIntExtra("dataIM2", 0);
String msg_nama = iIdentifikasi.getStringExtra("dataNama");
String msg_latin = iIdentifikasi.getStringExtra("dataLatin");
String msg_khasiat = iIdentifikasi.getStringExtra("dataKhasiat");
Im2 = (ImageView) findViewById(R.id.iv_detail2);
tv_nama = (TextView) findViewById(R.id.tvNama);
tv_latin = (TextView) findViewById(R.id.tvLatin);
tv_khasiat = (TextView) findViewById(R.id.tvKhasiat);
Im2.setImageResource(msg_im2);
tv_nama.setText(msg_nama);
tv_latin.setText(msg_latin);
tv_khasiat.setText(msg_khasiat);
}
}
activity_main.xml
<RelativeLayout 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:background="#FFF567"
android:orientation="vertical"
tools:context=".MainActivity" >
<EditText
android:id="#+id/et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/btn" >
<requestFocus />
</EditText>
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:onClick="search_db"
android:text="Search" />
<ListView
android:id="#+id/lv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/et" >
</ListView>
isi_lv.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"
android:orientation="vertical" >
<ImageView
android:id="#+id/imV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/tv_nama"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/imV"
android:text="TextView"
android:textSize="10pt" />
<TextView
android:id="#+id/tv_penyebab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tv_nama"
android:layout_below="#+id/tv_nama"
android:text="TextView" />
detail.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFF567"
android:orientation="vertical" >
<ImageView
android:id="#+id/iv_detail2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nama" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=":" />
<TextView
android:id="#+id/tvNama"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nama Latin" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=":" />
<TextView
android:id="#+id/tvLatin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</TableRow>
<TableRow
android:id="#+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Khasiat" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=":" />
<TextView
android:id="#+id/tvKhasiat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</TableRow>
</TableLayout>

If you wan to save the path, do what Telthien said.
If you want to save the file as a whole,You can save the data as BLOB type. http://www.sqlite.org/datatype3.html

Related

java programming language and android development

good evening dear friends, I'm working with SQLite db and android android applications I have a problem with my button when I click on login activity the message "could not execute for android onClick" my code are:
for LoginDatabaseAdapter.java class:
package com.delaroystudios.bus_seat_booking_system;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
/**
* Created by mugenzi israel on 9/19/2017.
*/
public class LoginDataBaseAdapter {
static final String DATABASE_NAME = "login.db";
static final int DATABASE_VERSION = 1;
static final String TABLE_NAME ="LOGIN";
public static final int NAME_COLUMN = 1;
static final String DATABASE_CREATE = "CREATE TABLE" + TABLE_NAME + "(" + " ID " + " INTEGER PRIMARY KEY AUTOINCREMENT," + " USERNAME text, PASSWORD text );";
public SQLiteDatabase db;
private Context context ;
private DataBaseHelper dbHelper;
public LoginDataBaseAdapter(Context _context){
Context context;
context = _context;
dbHelper = new DataBaseHelper(context,DATABASE_NAME,null,DATABASE_VERSION);
}
public LoginDataBaseAdapter open() throws SQLException{
db = dbHelper.getWritableDatabase();
return this;
}
public void close(){
db.close();
}
public SQLiteDatabase getDatabaseInstance(){
return db;
}
public void insertEntry(String userName,String password){
ContentValues newValues = new ContentValues();
newValues.put("USERNAME",userName);
newValues.put("PASSWORD",password);
db.insert("LOGIN",null,newValues);
}
public int deleteEntry(String UserName){
String where = "USERNAME=?";
int numberOFEntriesDeleted;
numberOFEntriesDeleted = db.delete(
"LOGIN",where, new String[]{
UserName}
);
return numberOFEntriesDeleted;
}
public String getSingleEntry(String userName){
Cursor cursor = db.query("LOGIN",null,"USERNAME=?",new String[]{userName},null,null,null);
if(cursor.getCount()<1){
cursor.close();
return "NOT EXIST";
}
cursor.moveToFirst();
String password = cursor.getString(cursor.getColumnIndex("PASSWORD"));
cursor.close();
return password;
}
public void updateEntry(String userName,String password){
ContentValues updatedValues = new ContentValues();
updatedValues.put("USERNAME",userName);
updatedValues.put("PASSWORD",password);
String where = "USERNAME = ?";
db.update("LOGIN",updatedValues,where,new String[]{userName});
}
}
code for DatabaseHelper.java class:
package com.delaroystudios.bus_seat_booking_system;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* Created by mugenzi israel on 9/19/2017.
*/
public class DataBaseHelper extends SQLiteOpenHelper {
public DataBaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version){
super(context,name,factory,version);
}
private static final String TABLE_NAME = "LOGIN";
static final String DATABASE_CREATE = "CREATE TABLE" + TABLE_NAME + "(" + " ID " + " INTEGER PRIMARY KEY AUTOINCREMENT," + " USERNAME text, PASSWORD text );";
#Override
public void onCreate(SQLiteDatabase _db){
_db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase _db,int _oldVersion,int _newVersion){
Log.w("TaskDBAdapter","Upgrading from version"+_oldVersion+"to"+_newVersion+
",which will destroy all old data") ;
_db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(_db);
}
}
code for Main_activity_login.java class:
package com.delaroystudios.bus_seat_booking_system;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class Main_activity_login extends AppCompatActivity {
Button login;
Button sign;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_login);
/* final Button login;
final Button sign;
LoginDataBaseAdapter loginDataBaseAdapter;*/
login = (Button)findViewById(R.id.log);
final Spinner spinner = (Spinner)findViewById(R.id.spinner1);
sign = (Button)findViewById(R.id.sgn);
loginDataBaseAdapter = new LoginDataBaseAdapter(this);
loginDataBaseAdapter = loginDataBaseAdapter.open();
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.roles_selection,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long l) {
Toast.makeText(getBaseContext(),parent.getItemAtPosition(position)+ "Selected",Toast.LENGTH_LONG).show();
((TextView) parent.getChildAt(0)).setTextColor(Color.RED);//TO change the color of spinner items
final Intent intent;
switch (position)
{
case 1:
intent = new Intent(Main_activity_login.this,Bus_info_admin.class);
startActivity(intent);
break;
case 2:
intent = new Intent(Main_activity_login.this,pick_ticket.class);
startActivity(intent);
break;
case 3:
intent = new Intent(Main_activity_login.this,SignIn.class);
startActivity(intent);
break;
case 4:
intent = new Intent(Main_activity_login.this,View_Booking.class);
startActivity(intent);
default:
System.out.println("wrong");
}
}
#Override
public void onNothingSelected(AdapterView<?> parent){
}
});
/* login.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v) {
// code for button one click
Intent intent = new Intent(Main_activity_login.this,DetailsLogin.class); startActivity(intent);
}
}
);*/
sign.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View view){
Intent intent = new Intent(Main_activity_login.this,SignIn.class);
startActivity(intent);
}
}
);
}
public void logIn(View v){
final Dialog dialog = new Dialog(Main_activity_login.this);
dialog.setContentView(R.layout.activity_main_login);//
dialog.setTitle("Login");
final EditText editUserName = (EditText)findViewById(R.id.EditLog);
final EditText editPassword = (EditText)findViewById(R.id.Edit_menu2);
Button btnLogin = (Button)findViewById(R.id.log);
final String userName,password,storedPassword;
userName = editUserName.getText().toString();
password = editPassword.getText().toString();
storedPassword = loginDataBaseAdapter.getSingleEntry(userName);
btnLogin.setOnClickListener(
new View.OnClickListener(){
public void onClick(View v){
if (password.equals(storedPassword)){
Toast.makeText(Main_activity_login.this,"You made it!,Login successful",Toast.LENGTH_LONG).show();
dialog.dismiss();
Intent intent = new Intent(Main_activity_login.this,DetailsLogin.class);
startActivity(intent);
}
else {
Toast.makeText(Main_activity_login.this,"User name or password does not match",Toast.LENGTH_LONG).show();
}
}
}
);
}
#Override
protected void onDestroy(){
super.onDestroy();
loginDataBaseAdapter.close();
}
/*public void startActivity() {
Intent intent = new Intent(Main_activity_login.this,Bus_info_admin.class);
startActivity(intent);
}*/
/*public void buttonLoginClick(View v){
Intent intent = new Intent(v.getContext(),DetailsLogin.class);
v.getContext().startActivity(intent);
}
*/
}
code for SignIn.java:
package com.delaroystudios.bus_seat_booking_system;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class SignIn extends AppCompatActivity { //AppCompatActivity
EditText editUserName,editPassword,editConfirmPassword;
Button btnCreateAccount,btn;
Context context = this;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
loginDataBaseAdapter = new LoginDataBaseAdapter(this);
loginDataBaseAdapter = loginDataBaseAdapter.open();
editUserName =(EditText)findViewById(R.id.id_name);
editPassword = (EditText)findViewById(R.id.email);
editConfirmPassword = (EditText)findViewById(R.id.password);
btnCreateAccount = (Button)findViewById(R.id.register) ;
btnCreateAccount.setOnClickListener(
new View.OnClickListener(){
public void onClick(View v){
String userName = editUserName.getText().toString();
String password = editPassword.getText().toString();
String confirmPassword = editConfirmPassword.getText().toString();
if (userName.equals("")||password.equals("")||confirmPassword.equals("")){
Toast.makeText(getApplicationContext(),"Field Vacant",Toast.LENGTH_LONG).show();
return;
}
if (!password.equals(confirmPassword)){
Toast.makeText(getApplicationContext(),"Password does not match",Toast.LENGTH_LONG).show();
return;
}
else {
loginDataBaseAdapter.insertEntry(userName,password);
Toast.makeText(getApplicationContext(),"Account Successfully created",Toast.LENGTH_LONG).show();
Intent i = new Intent(SignIn.this,Main_activity_login.class);
startActivity(i);
finish();
}
}
}
);
/*btn.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View view){
Intent intent = new Intent(SignIn.this,Main_activity_login.class);
startActivity(intent);
}
);*/
}
#Override
protected void onDestroy(){
super.onDestroy();
loginDataBaseAdapter.close();
}
}
code for sign_in.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.delaroystudios.bus_seat_booking_system.SignIn">
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="#string/register_here"
android:textSize="32sp"
android:gravity="center"
android:layout_marginTop="30dp"
/>
<EditText
android:layout_marginTop="40dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/user_id"
android:id="#+id/id_user"
/>
<EditText
android:layout_marginTop="30dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/full_name"
android:id="#+id/id_name"
/>
<EditText
android:layout_marginTop="30dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/phone_no"
android:id="#+id/phone"
/>
<EditText
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:hint="#string/email_id"
/>
<EditText
android:layout_marginTop="30dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/password"
android:id="#+id/password"
android:layout_marginBottom="20dp"
/>
<Button
android:id="#+id/register"
android:layout_width="150dp"
android:layout_height="50dp"
android:layout_gravity="center"
android:text="#string/register"
android:onClick="onClick"
/>
</LinearLayout>
code for activity_main_login.xml:
<?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="match_parent"
android:orientation="horizontal"
tools:context="com.delaroystudios.bus_seat_booking_system.Main_activity_login"
android:background="#drawable/bus1"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/menu1"
android:layout_marginBottom="100dp"
android:layout_marginTop="20dp"
android:gravity="center"
android:layout_marginStart="30dp"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/home"
android:textSize="20sp"
android:textColor="#9b59b6"
/>
<Button
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/about"
android:textColor="#9b59b6"
android:textSize="20sp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/contact"
android:textSize="20sp"
android:textColor="#9b59b6"
/>
<!--a verifier -->
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_below="#+id/menu1"
android:id="#+id/menu2"
android:layout_marginBottom="30dp"
>
<TextView
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="#string/Login2"
android:textSize="28sp"
android:textColor="#9b59b6"
/>
<EditText
android:id="#+id/EditLog"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/login"
android:textColorHint="#9b59b6"
android:textColor="#ffffff"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_below="#+id/menu2"
android:id="#+id/menu3"
android:layout_marginBottom="30dp"
>
<TextView
android:id="#+id/textView"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="#string/Pass"
android:textSize="28sp"
android:textColor="#9b59b6"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/your_password"
android:id="#+id/Edit_menu2"
android:textColorHint="#9b59b6"
android:textColor="#ffffff"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_below="#+id/menu3"
android:layout_marginBottom="10dp"
android:id="#+id/role"
>
<TextView
android:id="#+id/T_role"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="#string/role"
android:textSize="28sp"
android:textColor="#9b59b6"
/>
<Spinner
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/spinner1"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/men1"
android:layout_marginTop="70dp"
android:layout_below="#+id/role"
android:gravity="center"
android:layout_marginStart="30dp"
>
<Button
android:id="#+id/log"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginEnd="30dp"
android:onClick="logIn"
android:text="#string/login"
android:textColor="#9b59b6"
android:textColorHint="#9b59b6"
android:textSize="20sp"
/>
<Button
android:id="#+id/sgn"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginEnd="30dp"
android:onClick="onClick"
android:text="#string/sign_in"
android:textColor="#9b59b6"
android:textColorHint="#9b59b6"
android:textSize="20sp"
/>
In sign_in.xml,
<Button
android:id="#+id/register"
android:layout_width="150dp"
android:layout_height="50dp"
android:layout_gravity="center"
android:text="#string/register"
android:onClick="onClick"
/>
remove android:onClick="onClick" line. That should be work.

How to store images in SQLite and also how I can export input text and image in any tabular format?

1) Please help me out to store image submitted by button to SQLite.
2) How can I implement export function in my app so that all the input text and images stored in SQLite can be exported in any format but in tabular way so that exported file can be used to retrieve data again.
DatabaseHelper.java
package com.example.himanshu.instrumentalinformationcollector;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 3;
private static final String DATABASE_NAME = "instruments.db";
private static final String TABLE_NAME = "instrument_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NAME";
public static final String COL_3 = "LOCATION";
public static final String COL_4 = "INFORMATION";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String CREATE_TABLE="CREATE TABLE " + DatabaseHelper.TABLE_NAME + " (" +
DatabaseHelper.COL_1 + " INTEGER,"
+ DatabaseHelper.COL_2 + " TEXT,"
+ DatabaseHelper.COL_3 + " TEXT,"
+ DatabaseHelper.COL_4 + " TEXT);";
sqLiteDatabase.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " +DatabaseHelper.TABLE_NAME);
onCreate(sqLiteDatabase);
}
public boolean insertData(Integer ID, String name, String location, String information){
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.COL_1,ID);
contentValues.put(DatabaseHelper.COL_2,name);
contentValues.put(DatabaseHelper.COL_3,location);
contentValues.put(DatabaseHelper.COL_4,information);
sqLiteDatabase.insert(DatabaseHelper.TABLE_NAME,null,contentValues);
return true;
}
}
MainActivity.java
package com.example.himanshu.instrumentalinformationcollector;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.FileDescriptor;
import java.io.IOException;
public class MainActivity extends AppCompatActivity{
private static int RESULT_LOAD_IMAGE = 1;
DatabaseHelper myDB;
EditText editMessage,editMessage1,editMessage2,editMessage3;
Button submitData;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonLoadImage = (Button)findViewById(R.id.imgButton);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
myDB = new DatabaseHelper(this);
editMessage=(EditText)findViewById(R.id.editText);
editMessage1=(EditText)findViewById(R.id.editText1);
editMessage2=(EditText)findViewById(R.id.editText2);
editMessage3=(EditText)findViewById(R.id.editText3);
submitData=(Button)findViewById(R.id.submit);
AddData();
}
public void AddData(){
submitData.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v){
boolean isInserted = myDB.insertData(Integer.valueOf(editMessage.getText().toString()),editMessage1.getText().toString(),editMessage2.getText().toString(),editMessage3.getText().toString());
if(isInserted == true)
Toast.makeText(MainActivity.this,"Data Inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this,"Data not Inserted",Toast.LENGTH_LONG).show();
}
}
);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.img);
Bitmap bmp = null;
try {
bmp = getBitmapFromUri(selectedImage);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
imageView.setImageBitmap(bmp);
}
}
private Bitmap getBitmapFromUri(Uri uri) throws IOException {
ParcelFileDescriptor parcelFileDescriptor =
getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return image;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.himanshu.instrumentalinformationcollector.MainActivity">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_alignParentLeft="true"
android:layout_marginTop="30dp"
android:layout_marginLeft="16sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ID"
android:id="#+id/textView"
android:textColor="#android:color/black"
/>
<ImageView
android:layout_alignParentRight="true"
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/img"
android:background="#drawable/gray"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
/>
<Button
android:layout_alignParentRight="true"
android:layout_below="#id/img"
android:layout_marginRight="10dp"
android:id="#+id/imgButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:text="Upload"
android:textSize="16sp"
/>
<EditText
android:layout_marginTop="15dp"
android:id="#+id/editText"
android:layout_toRightOf="#id/textView"
android:layout_toLeftOf="#id/imgButton"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_marginLeft="45sp"
android:layout_marginRight="30sp"
android:hint="Please enter here"
android:maxLength="6"
android:textSize="16sp"
android:inputType="number"
/>
<TextView
android:layout_alignParentLeft="true"
android:layout_below="#id/textView"
android:layout_marginTop="50dp"
android:layout_marginLeft="16sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:textSize="16sp"
android:id="#+id/textView1"
android:textColor="#android:color/black"
/>
<EditText
android:id="#+id/editText1"
android:layout_marginTop="30dp"
android:layout_below="#id/editText"
android:layout_toRightOf="#id/textView1"
android:layout_toLeftOf="#id/imgButton"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_marginLeft="16sp"
android:hint="Full Name"
android:textSize="16sp"
android:inputType="textCapWords"
/>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:layout_marginTop="5dp"
android:layout_marginLeft="16sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Location"
android:textSize="16sp"
android:id="#+id/textView3"
android:textColor="#android:color/black"
/>
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Please enter here"
android:textSize="16sp"
android:inputType="textCapSentences"
android:layout_weight="1"
/>
</LinearLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp">
<TextView
android:layout_marginTop="16dp"
android:layout_marginLeft="16sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Information"
android:textSize="16sp"
android:id="#+id/textView2"
android:textColor="#android:color/black"
/>
<EditText
android:layout_alignParentLeft="true"
android:layout_toRightOf="#id/textView2"
android:layout_below="#id/textView2"
android:layout_marginTop="5dp"
android:layout_marginLeft="16sp"
android:id="#+id/editText3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine|textCapSentences"
android:gravity="top"
android:hint="Describe briefly"
android:textSize="16sp"
>
</EditText>
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="#+id/submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:layout_weight="1"
android:layout_marginRight="16dp"
android:layout_marginLeft="16dp"
/>
<Button
android:id="#+id/export"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Export"
android:layout_weight="1"
android:layout_marginRight="16dp"
android:layout_marginLeft="16dp"/>
</LinearLayout>
</LinearLayout>
The answer to your question is lengthy - and will require you to make many changes.
Saving Images:
If you want to save the images, you will need to convert the image to a byte array
A more feasible approach, is to save the image as a File within your app's internal storage, add a column to your database which saves the name of the image in a common directory "s8u903wmips.jpg" as an example.
Exporting Data:
Content Providers are created for exactly this reason. https://developer.android.com/guide/topics/providers/content-providers.html
Content providers are one of the primary building blocks of Android applications, providing content to applications. They encapsulate data and provide it to applications through the single ContentResolver interface. A content provider is only required if you need to share data between multiple applications. For example, the contacts data is used by multiple applications and must be stored in a content provider. If you don't need to share data amongst multiple applications you can use a database directly via SQLiteDatabase.

Android. How to change tab text color?

I want to set color of the tab text white, i cant find any good tutorial. Can someone help me?
There is my tab activity:
package com.example.dev.nordugrid;
import android.app.TabActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TabHost.TabSpec;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
#SuppressWarnings("deprecation")
public class Busena extends TabActivity {
SharedPreferences prefs;
TextView proxySuteike, proxyGaliojimas;
Button button4;
public int randomInt;
String stringProxyGaliojimas, stringProxySuteike, stringUzduotiesPav, stringUzduotiesJDL, stringKitiFailai;
Button holder;
private ArrayList<Item> m_parts = new ArrayList<Item>();
private Runnable viewParts;
private ItemAdapter m_adapter;
private final String data[] = { "Android", "iPhone", "BlackBerry", "AndroidPeople" };
private final String data2[] = { "Ivykdyta", "Atsaukta", "Einama", "Nusisnekejo" };
List<String> a = new ArrayList<String>();
List<String> b = new ArrayList<String>();
public static void setDefaults(String key, String value, Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key, value);
editor.commit();
}
public static String getDefaults(String key, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key, null);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.setContentView(R.layout.activity_busena);
this.setTheme(R.style.listItem);
holder = (Button)findViewById(R.id.button19);
proxyGaliojimas = (TextView)findViewById(R.id.generatenumber);
proxySuteike = (TextView) findViewById(R.id.textView5);
randomInt = Integer.parseInt(getDefaults("proxy", this));
stringProxySuteike = getDefaults("vo", this);
proxyGaliojimas.setText(randomInt + " min.");
proxySuteike.setText(stringProxySuteike);
stringUzduotiesPav = getDefaults("uzduotiesPav", this);
stringUzduotiesJDL = getDefaults("jdlFailoReiksme", this);
stringKitiFailai = getDefaults("kitiFailaiReiksme", this);
ListView list = (ListView)findViewById(R.id.tab1);
m_parts.add(new Item(stringUzduotiesPav, stringUzduotiesJDL));
m_adapter = new ItemAdapter(this, R.layout.row, m_parts);
list.setAdapter(m_adapter);
button4 = (Button) findViewById(R.id.refreshProxy);
TabHost tabHost = getTabHost();
this.setNewTab(this, tabHost, "tab1", R.string.uzduotys, android.R.drawable.star_on, R.id.tab1);
this.setNewTab(this, tabHost, "tab2", R.string.proxy, android.R.drawable.star_on, R.id.tab2);
addListenerOnButton();
}
/*#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String item = (String) getListAdapter().getItem(position);
Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show();
}*/
private void setNewTab(Context context, TabHost tabHost, String tag, int title, int icon, int contentID ) {
TabSpec tabSpec = tabHost.newTabSpec(tag);
String titleString = getString(title);
tabSpec.setIndicator(titleString, context.getResources().getDrawable(android.R.drawable.star_on));
tabSpec.setContent(contentID);
tabHost.addTab(tabSpec);
}
public void addListenerOnButton() {
button4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int skaicius = randomInt;
Random randomGenerator = new Random();
int rand = randomGenerator.nextInt(240-skaicius);
String ats = Integer.toString(randomInt);
proxyGaliojimas.setText(ats + " min.");
randomInt = rand;
}
});
}
}
And this is what I see :
This is tab activity xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.dev.nordugrid.Busena"
android:background="#drawable/background"
>
<TabHost
android:id="#android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TabWidget
android:theme="#style/listItem"
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"></TabWidget>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="#+id/tab1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" />
<LinearLayout
android:id="#+id/tab2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<!-- antro tabo vaizdas -->
<TextView
android:layout_marginTop="3dp"
android:id="#+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/proxyGaliojimas"
android:textColor="#FFFBFB"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:layout_marginLeft="7dp"
android:layout_marginTop="3dp"
android:id="#+id/generatenumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/min"
android:textColor="#FFFBFB"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:layout_marginTop="3dp"
android:id="#+id/textView4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/proxySuteike"
android:textColor="#FFFBFB"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:layout_marginLeft="7dp"
android:layout_marginTop="3dp"
android:id="#+id/textView5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/proxySuteike"
android:textColor="#FFFBFB"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:layout_marginTop="7dp"
android:id="#+id/refreshProxy"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/atnaujinti"
android:textColor="#FFFBFB"
android:background="#drawable/border"/>
</LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
Please someone give me simple example or other help :)
Create this method:-
private static View createTabView(Context context, String tabText) {
View view = LayoutInflater.from(context).inflate(R.layout.custom_tab, null, false);
TextView tv = (TextView) view.findViewById(R.id.tabTitleText);
tv.setText(tabText);
return view;
}
Create custom_tab.xml file in layout folder
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tabTitleText"
android:layout_width="#dimen/tabWidth"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:clickable="true"
android:paddingTop="#dimen/tabTopPading"
android:paddingBottom="#dimen/tabBottomPading"
android:paddingLeft="#dimen/tabLeftPading"
android:paddingRight="#dimen/tabRightPading"
android:textSize="#dimen/tabTextSize"
android:textColor="#color/themeColor"
android:background="#drawable/tab_selector"/>
finally set
tabHost.newTabSpec("Tab1").setIndicator(createTabView(getApplicationContext(),"Tab_name"))

how to make a slideshow from ArrayList of ImageURLs by using ViewFlipper in android?

I have made a simple demo android app,In that I am getting some Images url from the API,And I am filling an arrayList with them.I want to made a slideshow of that imageurl from the server ,I have seen the view flipper example but not getting how to do it in my case.
ViewFlipperAdapter.java
package com.epe.smaniquines.adapter;
import java.util.ArrayList;
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.LinearLayout;
import android.widget.TextView;
import com.epe.smaniquines.R;
import com.epe.smaniquines.adapter.CatalogAdapter.Viewholder;
import com.epe.smaniquines.util.Const;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
public class FlipperAdapter extends BaseAdapter {
ArrayList<String> urls;
private Context mContext;
private DisplayImageOptions options;
public static ImageLoader imageLoader;
public FlipperAdapter(Context paramContext, ArrayList<String> urls) {
this.urls = urls;
this.mContext = paramContext;
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(paramContext));
options = new DisplayImageOptions.Builder().cacheOnDisc(true)
.showStubImage(R.drawable.noimage)
.showImageOnFail(R.drawable.noimage).build();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return urls.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return urls.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext
.getSystemService("layout_inflater");
Viewholder localViewholder = null;
if (paramView == null) {
paramView = localLayoutInflater.inflate(R.layout.raw_flip,
paramViewGroup, false);
localViewholder = new Viewholder();
localViewholder.proImg = ((ImageView) paramView
.findViewById(R.id.iv_flip));
paramView.setTag(localViewholder);
} else {
localViewholder = new Viewholder();
localViewholder = (Viewholder) paramView.getTag();
}
imageLoader.displayImage(urls.get(paramInt), localViewholder.proImg,
options);
return paramView;
}
static class Viewholder {
ImageView proImg;
}
}
raw.flip
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="20dp" >
<ImageView
android:id="#+id/iv_flip"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
main.java
package com.epe.smaniquines.ui;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Timer;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterViewFlipper;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import com.epe.smaniquines.R;
import com.epe.smaniquines.adapter.FlipperAdapter;
import com.epe.smaniquines.util.Const;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
public class DetailsActivity extends Activity implements OnClickListener {
ImageView proImage, ivSave, ivInfo, ivPlay, ivBak, iv_share;
RelativeLayout rl_botm, rl_option;
TextView tv_facebuk, tv_twiter, tv_nothanks, tv_email, tv_save;
String big_img;
ArrayList<String> resultArray;
private DisplayImageOptions options;
public static ImageLoader imageLoader;
RelativeLayout rl_info;
public boolean flag = false;
int i = 0;
private int PicPosition;
private Handler handler = new Handler();
int mFlipping = 0;
ViewFlipper viewFlipper;
Timer timer;
int flagD = 0;
String data;
String shareType;
File image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_detail);
initialize();
/*
* Intent i = getIntent(); data = i.getStringExtra("data"); shareType =
* i.getStringExtra("type");
*/
big_img = getIntent().getStringExtra(Const.TAG_BIG_IMG);
resultArray = getIntent().getStringArrayListExtra("array");
System.out.println("::::::::::::::ArraySize::::::::" + resultArray);
imageLoader.displayImage(big_img, proImage, options);
ivInfo.setOnClickListener(this);
ivPlay.setOnClickListener(this);
tv_email.setOnClickListener(this);
tv_facebuk.setOnClickListener(this);
tv_nothanks.setOnClickListener(this);
tv_save.setOnClickListener(this);
tv_twiter.setOnClickListener(this);
iv_share.setOnClickListener(this);
ivBak.setOnClickListener(this);
// viewFlipper = (ViewFlipper) findViewById(R.id.flipper);
imageLoader.displayImage(big_img, proImage, options);
proImage.postDelayed(swapImage, 3000);
}
public void open(View view) {
/*
* Intent sharingIntent = new Intent(Intent.ACTION_SEND); screenshotUri
* = Uri.parse(big_img); sharingIntent.setType("image/*");
*/
/*
* sharingIntent .putExtra(Intent.EXTRA_TEXT,
* "Body text of the new status");
* sharingIntent.putExtra(Intent.EXTRA_TITLE, "Traffic At");
* sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
* startActivity(Intent.createChooser(sharingIntent,
* "Share image using"));
*/
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("*/*");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Hello test"); // <- String
Uri screenshotUri = Uri.parse(image.getPath());
shareIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
startActivity(Intent.createChooser(shareIntent, "Share image using"));
}
void initialize() {
proImage = (ImageView) findViewById(R.id.iv_det);
ivInfo = (ImageView) findViewById(R.id.iv_info);
ivPlay = (ImageView) findViewById(R.id.iv_play);
ivBak = (ImageView) findViewById(R.id.iv_back);
rl_botm = (RelativeLayout) findViewById(R.id.rl_bottom);
rl_option = (RelativeLayout) findViewById(R.id.rl_options);
tv_save = (TextView) findViewById(R.id.tv_save);
tv_email = (TextView) findViewById(R.id.tv_email);
tv_facebuk = (TextView) findViewById(R.id.tv_facebook);
tv_nothanks = (TextView) findViewById(R.id.tv_no_thanks);
tv_twiter = (TextView) findViewById(R.id.tv_twiter);
rl_option.setVisibility(View.GONE);
iv_share = (ImageView) findViewById(R.id.iv_share);
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration
.createDefault(DetailsActivity.this));
rl_info = (RelativeLayout) findViewById(R.id.rl_info);
rl_info.setVisibility(View.GONE);
resultArray = new ArrayList<String>();
}
#SuppressLint("NewApi")
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_share:
rl_option.setVisibility(View.VISIBLE);
break;
case R.id.iv_play:
proImage.setVisibility(View.GONE);
AdapterViewFlipper flipper = (AdapterViewFlipper) findViewById(R.id.flipper);
flipper.setAdapter(new FlipperAdapter(DetailsActivity.this,
resultArray));
break;
case R.id.iv_back:
finish();
break;
case R.id.tv_email:
rl_option.setVisibility(View.GONE);
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL,
new String[] { "youremail#yahoo.com" });
email.putExtra(Intent.EXTRA_SUBJECT, "subject");
email.putExtra(Intent.EXTRA_TEXT, "message");
email.setType("message/rfc822");
startActivity(Intent.createChooser(email,
"Choose an Email client :"));
break;
case R.id.tv_save:
save();
rl_option.setVisibility(View.GONE);
break;
case R.id.tv_facebook:
save();
open(v);
rl_option.setVisibility(View.GONE);
break;
case R.id.tv_no_thanks:
rl_option.setVisibility(View.GONE);
break;
case R.id.tv_twiter:
rl_option.setVisibility(View.GONE);
break;
case R.id.iv_info:
rl_option.setVisibility(View.GONE);
if (flag) {
rl_info.setVisibility(View.VISIBLE);
flag = false;
} else {
rl_info.setVisibility(View.GONE);
flag = true;
}
break;
}
}
// slide show..!!!
MediaPlayer introSound, bellSound;
Runnable swapImage = new Runnable() {
#Override
public void run() {
myslideshow();
handler.postDelayed(this, 1000);
}
};
private void myslideshow() {
PicPosition = resultArray.indexOf(big_img);
if (PicPosition >= resultArray.size())
PicPosition = resultArray.indexOf(big_img); // stop
else
resultArray.get(PicPosition);// move to the next gallery element.
}
//
// SAVE TO SD CARD..!!
void save() {
BitmapDrawable drawable = (BitmapDrawable) proImage.getDrawable();
Bitmap bitmap = drawable.getBitmap();
File sdCardDirectory = Environment.getExternalStorageDirectory();
File dir = new File(sdCardDirectory.getAbsolutePath()
+ "/3sManiquines/");
image = new File(sdCardDirectory, "3s_" + System.currentTimeMillis()
+ ".png");
dir.mkdirs();
boolean success = false;
// Encode the file as a PNG image.
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
addImageToGallery(dir + "", DetailsActivity.this);
Toast.makeText(getApplicationContext(), "Image saved with success",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during image saving", Toast.LENGTH_LONG).show();
}
}//
public static void addImageToGallery(final String filePath,
final Context context) {
ContentValues values = new ContentValues();
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(Images.Media.MIME_TYPE, "image/png");
values.put(MediaStore.MediaColumns.DATA, filePath);
context.getContentResolver().insert(Images.Media.EXTERNAL_CONTENT_URI,
values);
}
// facebook...
public void sharetext(String text) // Text to be shared
{
Intent share = new Intent(android.content.Intent.ACTION_SEND);
share.setType("text/plain");
share.putExtra(android.content.Intent.EXTRA_SUBJECT, "TITLE");
share.putExtra(android.content.Intent.EXTRA_TEXT, text);
startActivity(Intent.createChooser(share, "Share via"));
finish();
}
public void shareimage(String text) // argument is image file name with
// extention
{
Intent shareimage = new Intent(android.content.Intent.ACTION_SEND);
shareimage.setType("*/*");// for all
shareimage.setClassName("com.android.mms",
"com.android.mms.ui.ComposeMessageActivity");
shareimage.putExtra(Intent.EXTRA_STREAM, resultArray.indexOf(big_img));
startActivity(Intent.createChooser(shareimage, "Share Image"));
finish();
}
}
main.xaml
<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" >
<RelativeLayout
android:id="#+id/rl_det_hdr"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:background="#drawable/bottom_nav_bg" >
<ImageView
android:id="#+id/iv_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="5dp"
android:background="#drawable/btn_back" />
<TextView
android:id="#+id/titledetail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:padding="10dp"
android:text="CATALOG"
android:textColor="#ffffff"
android:textSize="18dp"
android:textStyle="bold" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/rl_main_det"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/rl_bottom"
android:layout_below="#+id/rl_det_hdr"
android:padding="10dp" >
<ImageView
android:id="#+id/iv_det"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerInParent="true" />
<AdapterViewFlipper
android:id="#+id/flipper"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/rl_options"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/rl_bottom"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#drawable/frame"
android:visibility="gone" >
<TextView
android:id="#+id/tv_twiter"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="10dp"
android:text="Twitter"
android:textColor="#1D88FC"
android:textSize="20dp" />
<View
android:id="#+id/sep1"
android:layout_width="fill_parent"
android:layout_height="0.75dp"
android:layout_below="#+id/tv_twiter"
android:background="#cecece" />
<TextView
android:id="#+id/tv_facebook"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/sep1"
android:gravity="center"
android:padding="10dp"
android:text="Facebook"
android:textColor="#1D88FC"
android:textSize="20dp" />
<View
android:id="#+id/sep2"
android:layout_width="fill_parent"
android:layout_height="0.75dp"
android:layout_below="#+id/tv_facebook"
android:background="#cecece" />
<TextView
android:id="#+id/tv_email"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/sep2"
android:gravity="center"
android:padding="10dp"
android:text="Email"
android:textColor="#1D88FC"
android:textSize="20dp" />
<View
android:id="#+id/sep3"
android:layout_width="fill_parent"
android:layout_height="0.75dp"
android:layout_below="#+id/tv_email"
android:background="#cecece" />
<TextView
android:id="#+id/tv_save"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/sep3"
android:gravity="center"
android:padding="10dp"
android:text="Save"
android:textColor="#1D88FC"
android:textSize="20dp" />
<View
android:id="#+id/sep4"
android:layout_width="fill_parent"
android:layout_height="0.75dp"
android:layout_below="#+id/tv_save"
android:background="#cecece" />
<TextView
android:id="#+id/tv_no_thanks"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/sep4"
android:gravity="center"
android:padding="10dp"
android:text="No Thanks"
android:textColor="#1D88FC"
android:textSize="20dp" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/rl_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/rl_bottom"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:background="#drawable/frame"
android:visibility="visible" >
<TextView
android:id="#+id/tv_twiter"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="left"
android:padding="10dp"
android:text="Info"
android:textColor="#000000"
android:textSize="16dp" />
<View
android:id="#+id/sep1"
android:layout_width="fill_parent"
android:layout_height="0.75dp"
android:layout_below="#+id/tv_twiter"
android:background="#cecece" />
<TextView
android:id="#+id/tv_facebook"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/sep1"
android:gravity="left"
android:padding="10dp"
android:text="Ead one Eno"
android:textColor="#1D88FC"
android:textSize="16dp" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/rl_bottom"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#drawable/bottom_nav_bg"
android:visibility="visible" >
<ImageView
android:id="#+id/iv_play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="#drawable/play_btn" />
<ImageView
android:id="#+id/iv_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:background="#drawable/about_us" />
<ImageView
android:id="#+id/iv_share"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:background="#drawable/share_icon" />
</RelativeLayout>
</RelativeLayout>
AdapterViewFlipper would be the best way to go since, in a ViewFlipper you need to pre define the views.
Inside onCreate :
ArrayList<String> urls;
//Fetch and set urls to this ArrayList;
AdapterViewFlipper flipper = (AdapterViewFlipper) findViewById(R.id.flipper);
flipper.setAdapter(new FlipperAdapter(urls));
FlipperAdapter.java
For loading image from urls, I'd suggest the use of the Universal Image Loader library : https://github.com/nostra13/Android-Universal-Image-Loader
public class FlipperAdapter extends BaseAdapter {
ArrayList<String> urls;
public FlipperAdapter(ArrayList<String> urls) {
this.urls = urls;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return urls.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return urls.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = (LinearLayout) LayoutInflater.inflate(
R.layout.viewLayout, parent, false);
}
ImageView image = (ImageView) convertView.findViewById(R.id.image);
imageLoader.displayImage(urls.get(position), image, null);
return convertView;
}
}
Edit 1 : viewLayout.xml (This will contain the layout of the items you want to display inside the adapterViewFlipper)
<?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">
<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>

How to View data, based on date input(edittext)?

I wanted to do a view output using table layout.
My idea goes like this.
I have a main page, known as activity_main.xml
when you click on the cancel button, it will go to a summary page,
know as data.xml.
In data.xml, I have a date edittext, whereby ,when I enter a date,eg 12/2/2013,
and after I click the button search, it will show me the record of it.
However, I'm not sure how to do it.
If I didn't enter any date and click "search", it will show all the records.
Right now,I am able to show all the records, without searching the data.
Below is my code.
Can someone kindly help me out with the search by date?
I hope that I've explained myself clear enough.
DBAdapter.java
public class DBAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_DATE = "date";
public static final String KEY_PRICE = "fuelprice";
public static final String KEY_FUEL = "fuelpump";
public static final String KEY_COST = "tcost";
public static final String KEY_ODM = "odometer";
public static final String KEY_CON = "fcon";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "MyDB";
private static final String DATABASE_TABLE = "fuelLog";
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE =
"create table fuelLog (_id integer primary key autoincrement, " + "date text not null, fuelprice text not null, fuelpump text not null, tcost text not null, odometer text not null, fcon text not null);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx){
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db)
{
try{
db.execSQL(DATABASE_CREATE);
}catch (SQLException e){
e.printStackTrace();
}
}//onCreate
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}//onUpgrade
}//DatabaseHelper
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}//open
//---closes the database---
public void close()
{
DBHelper.close();
}//close
//---insert a log into the database---
public long insertLog(String date, String fuelprice, String fuelpump,String tcost,String odometer,String fcon )
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_DATE, date);
initialValues.put(KEY_PRICE, fuelprice);
initialValues.put(KEY_FUEL, fuelpump);
initialValues.put(KEY_COST, tcost);
initialValues.put(KEY_ODM, odometer);
initialValues.put(KEY_CON, fcon);
return db.insert(DATABASE_TABLE, null, initialValues);
}//insertLog
// --retrieves all the data
public Cursor getAllLog()
{
return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_DATE, KEY_PRICE, KEY_FUEL,KEY_ODM,KEY_CON}, null, null, null, null, null);
}
}
summary.java
public class summary extends Activity{
TableLayout tablelayout_Log = null;
Button searchButton = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.data);
tablelayout_Log = (TableLayout) findViewById(R.id.tableLayout_Log);
tablelayout_Log.setStretchAllColumns(true);
tablelayout_Log.setShrinkAllColumns(true);
//View
searchButton = (Button) findViewById(R.id.searchBtn);
searchButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
try{
refreshTable();
}
catch (Exception e)
{
Log.d("Fuel Log", e.getMessage());
}
}
});
}//oncreate
public void refreshTable()
{
tablelayout_Log.removeAllViews();
TableRow rowTitle = new TableRow(this);
rowTitle.setGravity(Gravity.CENTER_HORIZONTAL);
TextView title = new TextView(this);
title.setText("Fuel Log");
title.setTextSize(TypedValue.COMPLEX_UNIT_DIP,18);
title.setGravity(Gravity.CENTER);
title.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
TableRow.LayoutParams params = new TableRow.LayoutParams();
params.span = 5;
rowTitle.addView(title, params);
tablelayout_Log.addView(rowTitle);
DBAdapter dbAdaptor = new DBAdapter(getApplicationContext());
Cursor cursor = null;
try
{
dbAdaptor.open();
cursor = dbAdaptor.getAllLog();
cursor.moveToFirst();
do{
long id = cursor.getLong(0);
String date = cursor.getString(1);
String price = cursor.getString(2);
String pump = cursor.getString(3);
String odometer = cursor.getString(4);
String fcon = cursor.getString(5);
TextView viewId = new TextView(getApplicationContext());
viewId.setText("" + id);
TextView viewDate = new TextView(getApplicationContext());
viewDate.setText(date);
TextView viewPrice = new TextView(getApplicationContext());
viewPrice.setText(price);
TextView viewPump = new TextView(getApplicationContext());
viewPump.setText(pump);
TextView viewOdometer = new TextView(getApplicationContext());
viewOdometer.setText(odometer);
TextView viewCon = new TextView(getApplicationContext());
viewCon.setText(fcon);
TableRow row = new TableRow(this);
row.setGravity(Gravity.CENTER_HORIZONTAL);
row.addView(viewId);
row.addView(viewDate);
row.addView(viewPrice);
row.addView(viewPump);
row.addView(viewOdometer);
row.addView(viewCon);
tablelayout_Log.addView(row);
}
while(cursor.moveToNext());
}
catch(Exception e){
Log.d("Fuel Log", e.getMessage());
}
finally
{
if (cursor != null)
cursor.close();
if(dbAdaptor != null)
dbAdaptor.close();
}
}//refreshTable
}//main
MainActivity.java
public class MainActivity extends Activity {
TableLayout tablelayout_Contacts = null;
Button insertButton = null;
EditText nameEdit = null;
EditText contactEdit = null;
Button viewButton = null;
Button deleteButton = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tablelayout_Contacts = (TableLayout) findViewById(R.id.tableLayout_Contacts);
tablelayout_Contacts.setStretchAllColumns(true);
tablelayout_Contacts.setShrinkAllColumns(true);
nameEdit = (EditText) findViewById(R.id.editText_Name);
contactEdit = (EditText) findViewById(R.id.editText_Number);
insertButton = (Button) findViewById(R.id.button1);
insertButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
DBAdapter dbAdaptor = new DBAdapter(getApplicationContext());
try{
dbAdaptor.open();
String name = nameEdit.getText().toString();
String number = contactEdit.getText().toString();
dbAdaptor.insertContact(name, number);
}
catch (Exception e)
{
Log.d("Contact Manager",e.getMessage());
}
finally{
if(dbAdaptor != null)
dbAdaptor.close();
}
}
});
//View records
viewButton = (Button) findViewById(R.id.button2);
viewButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
try{
refreshTable();
}
catch (Exception e)
{
Log.d("Contact Manager",e.getMessage());
}
}
});
//delete records
deleteButton = (Button) findViewById(R.id.button3);
deleteButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
DBAdapter dbAdaptor = new DBAdapter(getApplicationContext());
try{
refreshTable();
String name = nameEdit.getText().toString();
if(!name.equals(""))
{
dbAdaptor.deleteContact(name);
}
}
catch (Exception e)
{
Log.d("Contact Manager",e.getMessage());
}
}
});
}//oncreate
//refresh table
public void refreshTable()
{
tablelayout_Contacts.removeAllViews();
TableRow rowTitle = new TableRow(this);
rowTitle.setGravity(Gravity.CENTER_HORIZONTAL);
TextView title = new TextView(this);
title.setText("Contacts");
title.setTextSize(TypedValue.COMPLEX_UNIT_DIP,18);
title.setGravity(Gravity.CENTER);
title.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
TableRow.LayoutParams params = new TableRow.LayoutParams();
params.span =3;
rowTitle.addView(title,params);
tablelayout_Contacts.addView(rowTitle);
DBAdapter dbAdaptor = new DBAdapter(getApplicationContext());
Cursor cursor = null;
try{
dbAdaptor.open();
cursor = dbAdaptor.getAllContacts();
cursor.moveToFirst();
do{
long id = cursor.getLong(0);
String name = cursor.getString(1);
String contact = cursor.getString(2);
TextView idView = new TextView(getApplicationContext());
idView.setText("" + id);
TextView nameView = new TextView(getApplicationContext());
nameView.setText(name);
TextView contactView = new TextView(getApplicationContext());
nameView.setText(contact);
TableRow row = new TableRow(this);
row.setGravity(Gravity.CENTER_HORIZONTAL);
row.addView(idView);
row.addView(nameView);
row.addView(contactView);
tablelayout_Contacts.addView(row);
}
while (cursor.moveToNext());
}
catch (Exception e)
{
Log.d("Contact Manager", e.getMessage());
}
finally{
if (cursor != null)
cursor.close();
if(dbAdaptor != null)
dbAdaptor.close();
}
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:orientation="vertical"
android:layout_height="fill_parent"
tools:context=".MainActivity" >
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="1">
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/datetxtview"
android:text="#string/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/date"
android:text=""
android:inputType="date"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/fuelpricetxtview"
android:text="#string/fuelprice"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/fuelprice"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow3"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/fuelpumptxtview"
android:text="#string/fuelpump"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/fuelpump"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow4"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/totalcosttxtview"
android:text="#string/totalcost"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<TextView
android:id="#+id/tcost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</TableRow>
<TableRow
android:id="#+id/tableRow5"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/odometertxtview"
android:text="#string/odometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/odometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow6"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/fctxtview"
android:text="#string/fc"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<TextView
android:id="#+id/fcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</TableRow>
</TableLayout>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/saveBTN"
android:text="#string/save"
android:layout_width="wrap_content"
android:layout_height="60px" >
</Button>
<Button
android:id="#+id/updateBTN"
android:text="Update"
android:layout_width="wrap_content"
android:layout_height="60px" >
</Button>
<Button
android:id="#+id/cancelBTN"
android:text="#string/cancel"
android:layout_width="wrap_content"
android:layout_height="60px" >
</Button>
</LinearLayout>
</LinearLayout>
data.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TableLayout
android:id="#+id/tableLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="1">
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/datetxtview"
android:text="#string/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/datepast"
android:text=""
android:inputType="date"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/fctxtview"
android:text="#string/fc"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/fc"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow3"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/highpricetxtview"
android:text="#string/highprice"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/highprice"
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</EditText>
</TableRow>
<TableRow
android:id="#+id/tableRow4"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/searchBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search" />
<Button
android:id="#+id/deleteBTN"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete" />
<Button
android:id="#+id/backBTN"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back" />
</TableRow>
</TableLayout>
<TableLayout
android:id="#+id/tableLayout_Log"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</TableLayout>
</LinearLayout>
The error you are getting is a nullpointer that means that some object that is at line 205 in MainActivity or it is used at that line is null. Check that first and then try to run again.
The immediate problem is here:
catch (Exception e)
{
Log.d("Fuel Log", e.getMessage());
}
Not all throwables have a message and a null can be returned. A null cannot be logged. It causes the "println needs a message" exception in the stacktrace.
So first, change that to e.g.
catch (Exception e)
{
Log.e("Fuel Log", "", e);
}
This will log the exception with error level, empty message and with full stacktrace.
Then you can see what causes that exception in the first place.
Hello date type is not supported in Sqlite Database.you have assign date as text so it will take string so you need to keep string in proper order so that it can work as date search.
You can store date in form of 2013-12-23 (20131223) then you can get your query by passing date
by the way you can try like below
public ArrayList<String> getEventsForNotification(String dateSearch)
{
ArrayList<String> arrayList=new ArrayList<String>();
String sql="SELECT "+KEY_EVENT_NAME+" FROM "+ TABLE_EVENT +" WHERE SUBSTR("+KEY_EVENT_DATE+",6) like '"+dateSearch+"'";
Cursor cursor=sqLiteDatabase.rawQuery(sql, null);
if(cursor.moveToFirst())
{
do
{
arrayList.add(cursor.getString(0));
}while(cursor.moveToNext());
cursor.close();
cursor=null;
}
return arrayList;
}
modify according to your need.

Categories