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.
Related
so i have a project where im implementing a google sign in, i followed this tutorial on how to do that, but when i did, all my XML files appear blank. i made changes to the original MainActivity.java and the activity_main.xml file. i woudl think that only the activity_main.xml would be affected, but all of my XML files appear blank. when i try to run the app, i get
"Error:Content is not allowed in prolog.
" and
"Execution failed for task '.app:builderInfoDebugLoader'"
this is my activity main where i implement the google sign in:
package com.example.mayankthakur.personalprojecttrial2;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.auth.api.signin.SignInAccount;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import org.w3c.dom.Text;
public class MainActivity extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener {
private LinearLayout prof_section;
private Button SignOut;
private SignInButton SignIn;
private TextView Name,Email;
private ImageView Prof_Picture;
private Button continueBut;
private static final int REQ_CODE = 9001;
String name;
Intent nameSave;
private GoogleApiClient mGoogleApiClient;
public static final String prefsName = "com.example.mayankthakur.personalprojecttrial2";
private static final String TAG = "MainActivity";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
prof_section = (LinearLayout) findViewById(R.id.prof_section);
SignOut = (Button) findViewById(R.id.logoutBtn);
SignIn = (SignInButton) findViewById(R.id.gSignIn);
Name = (TextView) findViewById(R.id.nameSpace);
Email = (TextView) findViewById(R.id.emailSpace);
Prof_Picture = (ImageView) findViewById(R.id.profilePicture);
continueBut = (Button) findViewById(R.id.button2);
continueBut.setOnClickListener(this);
SignOut.setOnClickListener(this);
SignIn.setOnClickListener(this) ;
prof_section.setVisibility(View.GONE);
continueBut.setVisibility(View.GONE);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
}
#Override
public void onClick (View v) {
switch (v.getId()) {
case R.id.gSignIn:
signIn();
break;
case R.id.logoutBtn:
signOut();
break;
/*// This is the shared preference
SharedPreferences.Editor prefs = getSharedPreferences(prefsName, MODE_PRIVATE).edit();
//adding a value to the preference
prefs.putString("name", name);
prefs.apply();
nameSave = new Intent(MainActivity.this, Activity2.class);
MainActivity.this.startActivity(nameSave);
*/
}
}
#Override
public void onConnectionFailed (#NonNull ConnectionResult connectionResult){
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, REQ_CODE );
}
private void signOut(){
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
updateUI(false);
}
});
}
private void handleReuslt(GoogleSignInResult result){
if(result.isSuccess())
{
GoogleSignInAccount acct = result.getSignInAccount();
String personName = acct.getDisplayName();
String personEmail = acct.getEmail();
String imgUrl = acct.getPhotoUrl().toString();
String personId = acct.getId();
Uri personPhoto = acct.getPhotoUrl();
Name.setText(personName);
Email.setText(personEmail);
Glide.with(this).load(imgUrl).into(Prof_Picture);
updateUI(true);
}
else
{
updateUI(false);
}
}
private void updateUI(boolean isLogin){
if(isLogin)
{
prof_section.setVisibility(View.VISIBLE);
SignIn.setVisibility(View.GONE);
}
else
{
prof_section.setVisibility(View.GONE);
SignIn.setVisibility(View.VISIBLE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQ_CODE)
{
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleReuslt(result);
}
}
}
this is my XML file where i added the buttons and stuff for the google sign in:\
<?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:id="#+id/activity_main"
android:orientation="vertical"
tools:context="com.example.mayankthakur.personalprojecttrial2.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/prof_section"
android:layout_marginLeft="20dp"
android:layout_marginTop = "50dp"
android:weightSum="1">
<ImageView
android:id="#+id/profilePicture"
android:layout_width="90dp"
android:layout_height="100dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:src="#drawable/photo"
android:layout_weight="0.25" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginLeft="28dp"
android:layout_marginTop="20dp">
<TextView
android:id="#+id/nameSpace"
android:layout_width="166dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center_horizontal"
android:text="Name Display"
android:textSize="20dp"
android:textStyle="bold" />
<TextView
android:id="#+id/emailSpace"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="Email Display"
android:textSize="14dp"
android:textStyle="bold" />
<Button
android:id="#+id/logoutBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Logout" />
</LinearLayout>
</LinearLayout>
<com.google.android.gms.common.SignInButton
android:id="#+id/gSignIn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:layout_marginTop="60dp">
</com.google.android.gms.common.SignInButton>
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Please Sign in in order to make use of all of the features of the app"
android:textAlignment="center"
android:textSize="20dp"
android:layout_marginTop="30dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"/>
<Button
android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Continue"
android:layout_marginRight="50dp"
android:layout_marginLeft="50dp"
android:layout_marginTop="50dp"/>
</LinearLayout>
any help would be greatly appreciated, and if any of you require any more code please do ask
thanks in advance!
I have a MainActivity with a ListView and an add Button. When the user clicks the add Button it takes you to another activity the CreateActivity for you to enter in data or strings into the editText boxes. After that you click the create Button and it adds the strings to the ListView it shows up, but every time I try to add another item to the ListView it just overrides the first item and doesn't add on to the ListView.
MainActivity.java with listView and add button
package com.example.brian.inventoryapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static android.R.layout.simple_list_item_1;
public class MainActivity extends AppCompatActivity {
Button addButton;
ListView itemListView;
public static ArrayList<String> arrayList;
public static ArrayAdapter arrayAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle editTextData = getIntent().getExtras();
if(editTextData != null){
itemListView = (ListView)findViewById(R.id.itemListView);
String data = editTextData.getString("data");
arrayList = new ArrayList<String>();
arrayList.add(data);
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList);
itemListView.setAdapter(arrayAdapter);
if(data != ""){
arrayAdapter.notifyDataSetChanged();
}
}
addButton = (Button) findViewById(R.id.addButton);
addButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, CreateActivity.class);
startActivity(intent);
}
});
}
}
activity_main xml with listView and add button
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.brian.inventoryapp.MainActivity"
android:weightSum="1">
<Button
android:text="Add"
android:layout_width="wrap_content"
android:layout_height="58dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/addButton" />
<ListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/itemListView"
/>
</RelativeLayout>
CreateActivity.java with four editText boxes and create button
package com.example.brian.inventoryapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import static com.example.brian.inventoryapp.R.id.editTextItem;
public class CreateActivity extends AppCompatActivity {
EditText editTextItem;
EditText editTextModel;
EditText editTextSerial;
EditText editTextID;
Button createButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
getIntent();
editTextItem = (EditText)findViewById(R.id.editTextItem);
editTextModel = (EditText)findViewById(R.id.editTextModel);
editTextSerial = (EditText)findViewById(R.id.editTextSerial);
editTextID = (EditText)findViewById(R.id.editTextID);
createButton = (Button) findViewById(R.id.createButton);
createButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String item = "";
item = editTextItem.getText().toString().trim() +
editTextModel.getText().toString().trim() +
editTextSerial.getText().toString().trim() +
editTextID.getText().toString().trim();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("data", item);
startActivity(intent);
}
});
}
}
activity_create xml with the four editText boxes and the create button
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_create"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.brian.inventoryapp.CreateActivity">
<TextView
android:text="Item Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/textView" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/editTextItem" />
<TextView
android:text="Model Number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="18dp"
android:id="#+id/textView2"
android:layout_below="#+id/editTextItem"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:layout_below="#+id/textView2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/editTextModel" />
<TextView
android:text="Serial Number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editTextModel"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="18dp"
android:id="#+id/textView3" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:layout_below="#+id/textView3"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/editTextSerial" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="#mipmap/ic_launcher"
android:layout_below="#+id/editTextID"
android:layout_centerHorizontal="true"
android:layout_marginTop="64dp"
android:id="#+id/imageButton" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/editTextID"
android:layout_below="#+id/editTextSerial"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="18dp" />
<TextView
android:text="ID Number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView4"
android:layout_below="#+id/editTextSerial"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:text="Create"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/createButton"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
every time you restart the MainActivity, it is be created, the onCreate method was executed .one method you can use the comment method:use startactivityforResult;
you can read this question how to manage startactivityforResult.the second method is to set MainActivity model to SingleInstance.
You are starting MainActivity over and over again, clearing all data previously loaded.
Try this solution
Main activity:
package com.example.brian.inventoryapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static android.R.layout.simple_list_item_1;
public class MainActivity extends AppCompatActivity {
public static final int CREATE_REQUEST = 1;
private Button addButton;
private ListView itemListView;
private ArrayList<String> arrayList;
private ArrayAdapter<String> arrayAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
itemListView = (ListView) findViewById(R.id.itemListView);
addButton = (Button) findViewById(R.id.addButton);
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList);
itemListView.setAdapter(arrayAdapter);
addButton = (Button) findViewById(R.id.addButton);
addButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, CreateActivity.class);
startActivityForResult(intent, CREATE_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CREATE_REQUEST) {
if (resultCode == RESULT_OK) {
String item = data.getStringExtra("data");
arrayList.add(item);
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList);
itemListView.setAdapter(arrayAdapter);
}
}
}
}
In your CreateActivity change createButton listener to this one:
createButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String item = "";
item = editTextItem.getText().toString().trim() +
editTextModel.getText().toString().trim() +
editTextSerial.getText().toString().trim() +
editTextID.getText().toString().trim();
Intent intent = new Intent();
intent.putExtra("data", item);
setResult(RESULT_OK, intent);
finish();
}
});
Yes it will assume as if the MainActivity is started for the first time so you should use startActivityForResult() method instead of startActivity().This will continue your MainActivity and do not override your list View.
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.
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"))
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