android,eclipse,sqlite , How I create a DataBase in the Splash Screen on Android App?


How I create a DataBase in the Splash Screen on Android App?

Question:

Tag: android,eclipse,sqlite

How I create a DataBase in the SPLASH SCREEN?

Reason's:

I create a code who validate if my Table's and the Database exists, but this code CRASH when I try to read an inexistence Database (then, the app is closed), because I dont have a method to create.

I need create a database and Table "Users" if not exists (this is the case).

When the database exists and the table exists this app works very nice...

public class SplashScreenActivity extends Activity {

// Set the duration of the splash screen
private static final long SPLASH_SCREEN_DELAY = 2000;

final Context context = this;

UsersDataBaseAdapter loginDataBaseAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    loginDataBaseAdapter=new UsersDataBaseAdapter(this);
    loginDataBaseAdapter=loginDataBaseAdapter.open();

    // Set portrait orientation
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    // Hide title bar
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    setContentView(R.layout.splash_screen);

    TimerTask task = new TimerTask() {
        @Override
        public void run() {

            loginDataBaseAdapter=loginDataBaseAdapter.open();
            File dbtest =new File("/data/data/my.example.com/databases/database.db");
            if(dbtest.exists())
            {   
                boolean dbtest1 = UsersDataBaseAdapter.databaseExist();
                if (dbtest1==true){

                    Integer dbtest2= UsersDataBaseAdapter.ExisteTabla();
                    if (dbtest2==0 ){
                        Intent mainIntent = new Intent().setClass(SplashScreenActivity.this, HomeActivity.class);
                        startActivity(mainIntent);
                    }else{
                        Intent mainIntent = new Intent().setClass(SplashScreenActivity.this, HomeActivity.class);
                        startActivity(mainIntent);
                    }

                }else{
                    Intent mainIntent = new Intent().setClass(SplashScreenActivity.this, HomeActivity.class);
                    startActivity(mainIntent);
                }
            }else{





                Intent mainIntent = new Intent().setClass(SplashScreenActivity.this, HomeActivity.class);
                startActivity(mainIntent);
            }
            // Close the activity so the user won't able to go back this
            // activity pressing Back button
            finish();
        }
    };

    // Simulate a long loading process on application startup.
    Timer timer = new Timer();
    timer.schedule(task, SPLASH_SCREEN_DELAY);
}

}

Error message in Log

03-11 00:22:09.971: E/Trace(4411): error opening trace file: No such file or directory (2)
03-11 00:22:27.839: D/AndroidRuntime(4411): Shutting down VM
03-11 00:22:28.069: W/dalvikvm(4411): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
03-11 00:22:28.281: E/AndroidRuntime(4411): FATAL EXCEPTION: main
03-11 00:22:28.281: E/AndroidRuntime(4411): java.lang.RuntimeException: Unable to start activity ComponentInfo{br.exemplozxingintegration/com.example.skysoft.qr.SplashScreenActivity}: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
03-11 00:22:28.281: E/AndroidRuntime(4411):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
03-11 00:22:28.281: E/AndroidRuntime(4411):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-11 00:22:28.281: E/AndroidRuntime(4411):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-11 00:22:28.281: E/AndroidRuntime(4411):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-11 00:22:28.281: E/AndroidRuntime(4411):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-11 00:22:28.281: E/AndroidRuntime(4411):     at android.os.Looper.loop(Looper.java:137)
03-11 00:22:28.281: E/AndroidRuntime(4411):     at android.app.ActivityThread.main(ActivityThread.java:5041)
03-11 00:22:28.281: E/AndroidRuntime(4411):     at java.lang.reflect.Method.invokeNative(Native Method)
03-11 00:22:28.281: E/AndroidRuntime(4411):     at java.lang.reflect.Method.invoke(Method.java:511)
03-11 00:22:28.281: E/AndroidRuntime(4411):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-11 00:22:28.281: E/AndroidRuntime(4411):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-11 00:22:28.281: E/AndroidRuntime(4411):     at dalvik.system.NativeStart.main(Native Method)
03-11 00:22:28.281: E/AndroidRuntime(4411): Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
03-11 00:22:28.281: E/AndroidRuntime(4411):     at android.database.AbstractCursor.checkPosition(AbstractCursor.java:424)
03-11 00:22:28.281: E/AndroidRuntime(4411):     at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
03-11 00:22:28.281: E/AndroidRuntime(4411):     at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
03-11 00:22:28.281: E/AndroidRuntime(4411):     at com.example.skysoft.qr.UsersDataBaseAdapter.<init>(UsersDataBaseAdapter.java:56)
03-11 00:22:28.281: E/AndroidRuntime(4411):     at com.example.skysoft.qr.SplashScreenActivity.onCreate(SplashScreenActivity.java:28)
03-11 00:22:28.281: E/AndroidRuntime(4411):     at android.app.Activity.performCreate(Activity.java:5104)
03-11 00:22:28.281: E/AndroidRuntime(4411):     at     android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
03-11 00:22:28.281: E/AndroidRuntime(4411):     at     android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
03-11 00:22:28.281: E/AndroidRuntime(4411):     ... 11 more

My idea, is JUST CREATE the Database in the Splash Screen

UsersDataBaseAdapter.java

public class UsersDataBaseAdapter 
{       

    static final String DATABASE_NAME = "database.db";

    static final String LOGIN = "Users";
    String ID = "IdUser";
    String USERNAME = "UserName";
    String PASSWORD = "PASSWORD";
    String ETIQUETA = "Etiqueta";
    Integer COUNT = 0;
    static String PATH = "/data/data/my.example.com/databases/database.db";


    static final int DATABASE_VERSION = 1;
    public static final int NAME_COLUMN = 1;


    static final String DATABASE_CREATE = "CREATE TABLE IF NOT exists Users( IdUser INTEGER PRIMARY KEY,  UserName VARCHAR, PASSWORD  VARCHAR, Etiqueta VARCHAR); ";


    public static  SQLiteDatabase db;

    // Context of the application using the database.
    private final Context context;

    // Database open/upgrade helper
    private static DataBaseHelper dbHelper;

    public  UsersDataBaseAdapter(Context _context) 
    {
        context = _context;
        dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);

        if(db == null) db = dbHelper.getWritableDatabase();

        String Query = "Select IdUser, UserName, Etiqueta, PASSWORD From Users LIMIT 1";
        Cursor D = db.rawQuery(Query, null);

        D.moveToFirst();

        ID = D.getString(0);
        USERNAME = D.getString(1);
        ETIQUETA = D.getString(2);
        PASSWORD = D.getString(3);

        String QueryCheck= "select DISTINCT tbl_name from sqlite_master where tbl_name = '"+"Users"+"'";
        Cursor A = db.rawQuery(QueryCheck, null);
        A.getCount();

        if(A!=null) COUNT = A.getCount();

    }



    public  UsersDataBaseAdapter open() throws SQLException 
    {
        db = dbHelper.getWritableDatabase();
        return this;
    }

    public  UsersDataBaseAdapter read() throws SQLException 
    {
        db = dbHelper.getReadableDatabase();
        return this;
    }

    public void close() 
    {
        db.close();
    }

    public  SQLiteDatabase getDatabaseInstance()
    {
        return db;
    }



    public void insertRecords(String userName,String password, Integer uid)
    {
       ContentValues newValues = new ContentValues();

       // Asigna los valores para cada "row" (la fila).
        newValues.put(USERNAME, userName);
        newValues.put(PASSWORD, password);
        newValues.put(ID, uid);

        // Inserta el "row" (la fila) en la tabla
        db.insert(LOGIN, null, newValues);
        ///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
    }

    public void updateEti(String userName, String etiqueta)
    {
        // Define la actualización del contenido del "row" (fila).
        ContentValues updatedValues = new ContentValues();
        // Asigna los valores de cada "row" (fila).
        updatedValues.put(USERNAME, userName);
        updatedValues.put(ETIQUETA, etiqueta);

        String where=USERNAME+" = ?";
        db.update(LOGIN,updatedValues, where, new String[]{userName});             
    }

    //
    public static Boolean CheckTable() {

        SQLiteDatabase helppo = db;
        Cursor cursor = helppo.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = '"+LOGIN+"'", null);
        if(cursor!=null) {
            if(cursor.getCount()>0) {
                                cursor.close();
                return true;
            }
                        cursor.close();
        }
        return false;

    }


    public String CheckEtiqueta(String LOGIN2) {

        String Query = "Select * Form Users LIMIT 1";

        Cursor c = db.rawQuery(Query, null);

        while (c.moveToNext()) {
             //Sample operation with the Database
             if (c.getString(c.getColumnIndex("IdUser"))!=null) { 

                   return c.getString(c.getColumnIndex("IdUser"));
             }
        }
        return c.getString(c.getColumnIndex("IdUser"));

    }

    public static String getIDUsuario(){
        String Query = "Select * From Users LIMIT 1";
        Cursor D = db.rawQuery(Query, null);

        D.moveToFirst();

        String Var1 = D.getString(0);

        return Var1;
    }

    public static String getUsuario(){
        String Query = "Select * From Users LIMIT 1";
        Cursor D = db.rawQuery(Query, null);

        D.moveToFirst();

        String Var1 = D.getString(1);

        return Var1;
    }

    public static String getPassword(){
        String Query = "Select * From Users LIMIT 1";
        Cursor D = db.rawQuery(Query, null);

        D.moveToFirst();

        String Var1 = D.getString(2);

        return Var1;
    }

    public static String getEtiqueta(){
        String Query = "Select * From Users LIMIT 1";
        Cursor D = db.rawQuery(Query, null);

        D.moveToFirst();

        String Var1 = D.getString(3);

        return Var1;
    }


    public static boolean checkDataBase() {
        SQLiteDatabase checkDB = null;
        try {
            checkDB = SQLiteDatabase.openDatabase("/data/data/my.example.com/databases/database.db", null,
                    SQLiteDatabase.OPEN_READONLY);
            checkDB.close();
        } catch (SQLiteException e) {
            // database doesn't exist yet.
        }
        return checkDB != null ? true : false;
    }



    public static SQLiteDatabase getReadableDatabase() {
        db = dbHelper.getReadableDatabase();
        return db;
    }

    public static boolean databaseExist()
    {

        String DB_PATH=PATH;

        SQLiteDatabase checkDB = null;
        try {
            checkDB = SQLiteDatabase.openDatabase(DB_PATH, null, SQLiteDatabase.OPEN_READONLY);
            checkDB.close();
            return true;
        }
        catch(SQLiteException e) {
            // Log an info message stating database doesn't exist.
        }

        return false;
    }

    boolean isTableExists(SQLiteDatabase db, String tableName) 
    {
        if (tableName == null || db == null || !db.isOpen()) {
            return false; 
            }
        Cursor cursor = db.rawQuery("SELECT COUNT(*) FROM sqlite_master WHERE type = ? AND name = ?", 
                new String[] {"table", tableName});
        if (!cursor.moveToFirst()) 
        {
            return false; 
        } 
        int count = cursor.getInt(0); 
        cursor.close(); 
        return count > 0; 
    }

    public static int ExisteTabla(){

        String Query = "Select * From Users LIMIT 1";
        Cursor D = db.rawQuery(Query, null);

        D.moveToFirst();
        int Var1 = D.getCount();

        return Var1;
    }

DataBaseHelper.java

    public class DataBaseHelper extends SQLiteOpenHelper
    {

    public DataBaseHelper(Context context, String name,CursorFactory factory, int version) 
        {
               super(context, name, factory, version);
}
    // Manda llamar cuando la base de datos  NO existe en disco y el "helper class" (La clase auxiliar) requiere
    // crear uno nuevo.

@Override
public void onCreate(SQLiteDatabase _db) 
{
        _db.execSQL(UsersDataBaseAdapter.DATABASE_CREATE);

}
// Called when there is a database version mismatch meaning that the version
// of the database on disk needs to be upgraded to the current version.
@Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion) 
{
        // Log the version upgrade.
        Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to " +_newVersion + ", which will destroy all old data");


        // Actualiza la base de datos existente para conformar la nueva version. Multiple
        // Puede realizar por comparacion de los valores entre los _oldVersion y _newVersion
        // The simplest case is to drop the old table and create a new one.
        _db.execSQL("DROP TABLE IF EXISTS " + "TEMPLATE");
        // Create a new one.
        onCreate(_db);
}

}


Answer:

The error is probably you do not have any data in the database which makes D.moveToFirst(); caused an error

change it to

if (D.moveToFirst()){
    ID = D.getString(0);
    USERNAME = D.getString(1);
    ETIQUETA = D.getString(2);
    PASSWORD = D.getString(3);
}

Related:


Android Espresso: Test running failed. No test results Empty test suite. Why?


android,android-espresso
Can't make my Espresso UI test work. Where's the problem? What result should I get for this simple app to consider that it's working? I have "android.support.test.runner.AndroidJUnitRunner" for Instrumentation runner in Edit Confirurations. From AndroidManifest.xml: <instrumentation android:name="android.support.test.runner.AndroidJUnitRunner" android:targetPackage="my.package"/> From build.gradle: defaultConfig { applicationId "my.package" minSdkVersion 18 targetSdkVersion 22 versionCode 1...

Robolectric 3 : Load test specific resource


android,unit-testing,robolectric
I'm using Robolectric 3 and I'm trying to load some resources that are in my test/res/ folder. Here is my file hierarchy : project/ |-src/ |--main/ |---AndroidManifest.xml |---res/ |----raw/ |-----prod.json |--test/ |---java/ |----com.app/ |-----CustomTestRunner.java |-----Mytest.java |---res/ |----raw/ |-----test.json I would like in MyTest.java to do something like RuntimeEnvironment.application.getResources().openRawResource(R.raw.test); but i...

Add a ListView or RecyclerView to new NavigationView


android,listview,recyclerview,navigationview
I am using the new NavigationView from revision 22.2.0 of the support library by Google. It works perfectly fine to generate a navigation drawer populated using a menu res. I was wondering is it possible to add a ListView or RecyclerView to the navigation drawer so that it can be...

How to set speaker phone off when the app is killed by the “Recent App drawer”


android,android-audiomanager,ondestroy
I implemented an app which has a button speaker, which is manually set "on" by myAudioManager.setSpeakerphoneOn(true) and "off" vice-versa. But the bug is when you close the application while the speaker is on, it forgets the speaker was on. The next time, the speaker remains on and the call is...

Android String if-statement


java,android,string
I have a if-statement in the start of my app if (ready.equals("yes")){ ... } and later on my code I have ready="yes"; but the if statement is never called, why? The ready="yes"; is called from a background thread, is that why? public void DownloadFromUrl(final String fileName) { //this is the...

custom arraylist get distinct


java,android
is there any way to get the distinct values of a custom arraylist? public class mystatistic extends BaseActivity { public String objectid; public String playerid; public String playername; public String enemyid; public String enemyname; public String question; public mystatistik(String objectid, String playerid, String playername, String enemyid, String enemyname, String question)...

setOnClickListener error Null object


java,android
I saw many questions like mine and I try to fix my codes but failed... this is my code: public class MainActivity extends ActionBarActivity { EditText usernameEditText; EditText passwordEditText; public Button saveme; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); usernameEditText = (EditText) findViewById(R.id.username); passwordEditText = (EditText) findViewById(R.id.pass); saveme = (Button)...

why is Android app publishing taking several days [on hold]


android,google-play,publishing
I have uploaded my app on the store 3 days ago and it status still : PENDING PUBLICATION I have uploaded all the app listing needed : description, screen shots ... and google didn't contact me on E-mail. does anyone had the same case before ???...

echo json_encode after mysql_query failure


php,android
I'm currently trying to develop an Android app that communicates with a database. I use php scripts to communicate between my app and the database. For error handling purposes, I was wondering if I could replace the die() function in php with something simliar to json_encode so that I can...

Blank screen on GridView


android,arrays,gridview
I'm trying to create a GridView with an array of strings. These are XML, and MainActivity and Adapter, but what I get is a blank screen. I'm change the background, but the result is the same, but clicking on a point on the screen appears to me the toast stating...

Android Implicit Intent for Viewing a Video File


java,android,android-intent,uri,avd
In my Android app, I have a button that when clicked, launches the external application of my choice to play a video (I gather that this is called an "implicit intent"). Here is the relevant Java code from my onCreate method. Button button = (Button) findViewById(R.id.button); button.setOnClickListener ( new Button.OnClickListener()...

Dagger 2 Custom Scope for each Fragment


android,android-fragments,dagger-2
I'm a little confused about how to best use the custom scoping in Dagger 2. I've looked at a couple different articles which seem to suggest two different ways of doing it: MVP Presenters that Survive Configuration Changes Part-2 (Github repo): Uses unique custom scopes for each fragment, e.g. @Hello1Scope...

Fixed element in android?


android,xml,android-fragments
I am using a FAB(Floating action button) and a ViewPager that has a list inside a fragment. The ViewPager stops due to the FAB block and each are blocks the ViewPager being on top of the FAB activity_main.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:fab="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:fitsSystemWindows="true">...

Notification whenever a new topic is created on mosquitto


android,mqtt,mosquitto,libmosquitto
I am trying to implement Push notifications on Android, using Mosquitto broker. So, different android application create topics based on tehir id on which they will receive notifications. To send notifications to those android applications we need the name of the topic. I am wondering if there is a way...

Mysterious claim of a missing { in eclipse


java,eclipse
I have a case of a mysterious missing curly brace that I don't see any use for. Eclipse says, "Syntax error on token ";", { expected after this token". Either I am missing something very silly or there is something new I have to learn about Java. This is the...

error: cannot find symbol class AsyncCallWS Android


java,android,web-services
I'm trying to rewrite the application in this, in Android Studio link, which is written in Eclipse. There are two problems, first problem is there is this line in the project : import com.example.webserviceactivity.R; I couldn't write this one on Android Studio. The second problem is, in this part of...

Twitter4j - cannot resolve method - setUsessl(boolean)


android,android-studio,twitter4j
I'm using twitter4j 4.0.3 core I have this code: public final class TwitterUtil { private RequestToken requestToken = null; private TwitterFactory twitterFactory = null; private Twitter twitter; private TwitterUtil() { ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.setOAuthConsumerKey(ConstantValues.TWITTER_CONSUMER_KEY); configurationBuilder.setOAuthConsumerSecret(ConstantValues.TWITTER_CONSUMER_SECRET); configurationBuilder.setUseSSL(true); Configuration configuration =...

Disable Wrapping Cursor in Eclipse


eclipse,vim,vi
I'm mostly using Vi (edit: Vim) for text editing and the viPlugin for Eclipse Juno. Eclipse seems to have a very annoying behaviour of "wrapping" the cursor to the next/previous line, if yout reach the end/start of a line through cursor keys. (Reproduce by placing the cursor on the first...

how does android ImageView resize my image?


android
I have some 100*100 icons and I cannot find better resolution icons so I put them inside drawable folder. The width and height of the image view are set to wrap_content. When the image is shown on a xhdpi screen will the image be scaled to 200*200 automatically? or should...

Why i get can not resolve method error in class android?


android,json
I use this tutorial: JSON and part of code to this: protected String doInBackground(String... urls) { TextView lbl=(TextView) findViewById(R.id.provCODE); person = new Person(); person.setName(lbl.getText().toString()); //person.setCountry("1853"); //person.setTwitter("1892"); return POST(urls[0],person); } but in the this line: person.setName(lbl.getText().toString()); i get this error: Can not resolve method. How can i solve that?what happen? my...

how to add menu items to action bar in more than 30 activities


android,android-activity,android-studio,menu,menuitem
I have created an app in android studio that has more than 30 activities .I created menu items in some activities by adding them in individual menu files and they worked fine . But the problem is that it is a real headache to add all the menu items in...

adapter.notifyDataSetChanged() not working when I update ArrayList


android,android-listview
I have seen a lot of post about this case but I don't find a solution for me. I use SwipeRefreshLayout.OnRefreshListener and this is my code in onRefresh() method. This doesn't work. new Handler().postDelayed(new Runnable() { @Override public void run() { Aviso aviso = new Aviso(); aviso.setTitle("MMMMMMMMMMMMMMMMMMMMMM"); aviso.setDescription("Deskribapena"); aviso.setPubDate("Wed, 19...

Android custom calendar view disable specific dates


android,calendarview
i'm new to android developing and started to develop an booking app. There is a calendar view and i want to disable booked dates in that calendar. I found out that disabling feature is not there in android default calendar. so could you please help me to find a good...

Can I install 2 or more Android SDK when using Eclipse


java,android,eclipse,sdk,versions
I am new to android developments. I am setting up my android development environment using Eclipse. I have a test smart phone with Android version 4.2.2. The automatic installation installed the latest Android SDK version, which is 5.1.1. My questions are: 1. Do I have to install the SDK version...

Unfortunately, (My app) has stopped. Eclipse Android [duplicate]


java,android,eclipse,adt
This question already has an answer here: What is a Null Pointer Exception, and how do I fix it? 12 answers I'm a beginner in android developing and I'm trying to build a simple app but I'm getting this error in the emulator.(Unfortunately,(App) has unexpectedly stopped). LogCat http://i.stack.imgur.com/VZhuL.png package...

How to resolve Out of Memory Error on Bitmap in Android?


android,android-intent,android-activity,bitmap
I want to set an image in image view,I am retrieving the image path in my first activity and I am passing it via intent as a String to second activity.In the second activity I set the path to an image view,It is working properly , and I need to...

Facebook Android API asks for additional permission


android,facebook,facebook-graph-api
I am using v2.3 api here I can login with Facebook login button. Now how can I call additional permission on click? I have looked through answers for this question, but all of them look to be back-dated. Can someone show me the right way of asking for addition permission...

Passing dynamic string resource to “setText()”


android
I am trying to make a dynamic string and converting a hardcoded string which has been passed to setText() function . However it doesn't seem to accept it . Here is what I have tried : Original code : device.name.setText("Mac :" + data.macAddress); Strings.xml declaration : <string name="mac">Mac :</string> New...

Getting particular view from expandable listview


java,android,listview,android-fragments,expandablelistview
In my list view I have an textview in expandable group and I want to open the dialog when textview is clicked to fill the information through edittext and update textview. Problem: how could I get the groupview textview item in my fragment oncreateview() method....

Get current latitude and longitude android


java,android,gps,geolocation,location
Requirement: 1.Sometimes(not everytime) I am getting latitude and longitude 0.0. 2.I want to know how to get the location update after user has enabled the gps from the settings. Here is my code public class GPSTracker extends Service implements LocationListener { private final Context mContext; // flag for GPS status...

Is there any sdk to log exceptions, events and errors in production app?


android,logging,error-handling,sdk,production
I want to catch all the un expected/undesirable events in my app during production. I want something which can send a error log file to server and I can easily read it through a web application. Do you know anything of this sort ?

Android programming, draw a rectangle with specific coordinates


android
I am new to android programming. I am trying to draw a rectangle as in the image below. I have no idea how to do it with Rect(int left, int top, int right, int bottom). Can someone help me with this thanks. ...

Contexts and callbacks from asynchronous tasks


android,android-fragments,asynchronous
I've been experiencing this problem on some devices, especially Samsung. I have an activity that has 7 fragments. In most of them, I start an async task for getting some data. I handle the exceptions by creating a handler in onCreateView(). handler = new Handler(new Handler.Callback() { @Override public boolean...

Problems implementing ViewHolder pattern


android,design-patterns
I'm working on an android app from a book. I'm getting errors : "crimeHolder cannot be resolved" and I can't understand why.. public View getView(int poisition, View convertView , ViewGroup parent) { //If we weren't given a view, inflate one if (convertView == null) { convertView = getActivity().getLayoutInflater().inflate(R.layout.list_item_crime, null); ViewHolder...

Is there any way to use a pre-existing database from Xamarin without copying it from Assets?


android,xamarin,xamarin.forms
I have a rather large SQLite database (~20 mb) I need to access from my Android Xamarin-Forms app. Everything online I've read says you can read the database by copying it to the filesystem first. For example, this question. However, won't that mean the large database is duplicated, wasting users'...

Get element starting with letter from List


java,android,list,indexof
I have a list and I want to get the position of the string which starts with specific letter. I am trying this code, but it isn't working. List<String> sp = Arrays.asList(splited); int i2 = sp.indexOf("^w.*$"); ...

How to force team members to comment using eclipse plugin or something else


eclipse,jenkins,eclipse-plugin,coding-style,build-automation
Currently, I am working in a new project and it was difficult for me to understand since there is no comment. I wonder if it is possible to force team members(including me) to add more comments. I would like to automate this ject in jenkins later if possible.

BitmapFont class does not have getBound(String) method


java,android,libgdx
Previously I used getBound method for BitmapFont class in libgdx, but now, I am unable to use it. I cannot find the changes in latest version. Any help is appreciated. Thank you...

How to restrict file copying shared using Content Provider in Android?


android,security
Is it possible to forbid making copies of files for third party applications (like adobe reader), that I am using to open pdf files stored in internal memory of my application?

Set value for Spinner with custom Adapter in Android


android,dynamic,android-arrayadapter,android-spinner
I am developing a android application with spinner in a form. The spinner items and spinner values are different. I want to collect all the value from the from including spinner and set a rest api service to web back end. here is the response array. {"Status":true,"errorType":null,"countryList":[{"Code":"US","Name":"United States"},{"Code":"CA","Name":"Canada"},{"Code":"AU","Name":"Australia"},{"Code":"GB","Name":"United Kingdom"}]} I...

Action Bar activity is closed


android,android-actionbar
What is wrong with my code? When I run application on my device/emulator my application is crashed " Unfortunately! Action Bar has stopped" public class Main extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ActionBar mActionBar = getActionBar(); assert mActionBar != null; mActionBar.setDisplayShowHomeEnabled(false); mActionBar.setDisplayShowTitleEnabled(false); LayoutInflater mInflater =...

Action view intent does not work


android,search-suggestion,custom-search-provider
Action view Intent for Search widget does not send Intent i am using Toast to show whether intent is sent when user choose item from suggestion in Quick Search Box here is snippet where intent is received in searchable Activity if (Intent.ACTION_VIEW.equals(intent.getAction())){ /* Intent countryIntent = new Intent(this, RecordActivity.class); countryIntent.setData(intent.getData());...

android imageView scale


android,imageview,scale
I have an ImageView which is populated from database (the image comes from database). in the database i have images both portrait and landscape!! how can i adjust the imageView to scale it self according to the image width and height. I have tried many ways but no result! any...

Crop does not work for gallery images


android,image,crop
I am using the following code to crop images from camera and gallery : private void doCrop() { final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>(); Intent intent = new Intent("com.android.camera.action.CROP"); intent.setType("image/*"); List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, 0); int size = list.size(); if (size == 0) { Toast.makeText(this, getApplicationContext().getString(R.string.crop_unavailable), Toast.LENGTH_SHORT).show(); // return }...

Keep HashMap with object data while app is idle - Android


android,android-activity
I have a HashMap that contains data relevant to a specific Activity. The problem is that when the app is opened after being idle for some time, the HashMap is empty. I am fetching all the data in the main activity and storing the corresponding objects in a HashMap in...

Bluetooth pairing - how to show the simple Cancel/Pair dialog?


android,android-intent,bluetooth,android-bluetooth,bluetooth-oob
I have prepared a simple test project for this question at GitHub. I am trying to create an Android app, which would scan a QR code from a computer screen and then use the data (MAC address and PIN or hash) for easy pairing (bonding) with a Bluetooth device. Similar...

Android set clickable text to go one fragment to another fragment


java,android,android-fragments,spannablestring
I need to do something like this. Suppose I have 2 fragments A and B.There is a text which can be clickable in fragment A and when user click this text , he can go to fragment B. This example helped me to do it but I think it does...

Floating Action Button in Xamarin.Forms


android,xamarin,monodroid,xamarin.forms,floating-action-button
I had completed my App's home page in Xamarin.Forms Portable. Now i want to add a Flotation Action Button In my Android Project ! Is there any way to add FAB for Android in my existing home page, which was coded in Xamarin.Forms Portable. OR I want to create a...