2

Ive created an app that is just making data accessible on mobile devices. This is what should happen.

1) connect to MySQL db

2) pull data from MySQL db

3) save data to SQLite db

4) display data from SQLite db

This all works good and well when I have net access. but it seems the moment I loose my connectivity I can no longer access data from my SQLite db.... and the whole point of the app is to make data accessible anywhere, with or without internet, hence the local db. Hope someone can help me with this...

public class MainActivity extends Activity {
    SQLiteDatabase HRdb;

    InputStream isr = null;
    String result = "";
    TextView resultView;

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        HRdb=openOrCreateDatabase("HRdb",MODE_PRIVATE,null);
        HRdb.execSQL("CREATE TABLE IF NOT EXISTS HRinfotbl (lname VARCHAR, fname VARCHAR, email VARCHAR, contact VARCHAR);");

        try {
            result = new httprRequest().execute().get();
            HRdb.delete("HRinfotbl", null, null);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        resultView = (TextView) findViewById(R.id.result);
        getData();



    }

/*
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
*/

    //function to print data from SQLite array
    public String SQLitePrint(String n)
    {
        String info = "";
        Cursor c=HRdb.rawQuery("SELECT * from "+n+";", null);
        int count = c.getCount();
        c.moveToFirst();

        for (Integer j = 0; j < count; j++)
        {
            info = info + 
                       "Surname : "+c.getString(c.getColumnIndex("lname"))+"\n"+
                       "Name : "+c.getString(c.getColumnIndex("fname"))+"\n"+
                       "Email : "+c.getString(c.getColumnIndex("email"))+"\n"+
                       "Contact : "+c.getString(c.getColumnIndex("contact"))+"\n\n";
            c.moveToNext() ;
        }
        HRdb.close();
        return info;

    }

    public String Search(String n)
    {
        String info = "";
        Cursor cu = HRdb.rawQuery("SELECT * FROM HRinfotbl WHERE (lname LIKE '%||"+n+"||%' OR fname LIKE '%||"+n+"||%';",null);
        int count = cu.getCount();
        cu.moveToFirst();
        for (Integer j = 0; j < count; j++)
        {
            info = info + 
                       "Surname : "+cu.getString(cu.getColumnIndex("lname"))+"\n"+
                       "Name : "+cu.getString(cu.getColumnIndex("fname"))+"\n"+
                       "Email : "+cu.getString(cu.getColumnIndex("email"))+"\n"+
                       "Contact : "+cu.getString(cu.getColumnIndex("contact"))+"\n\n";
            cu.moveToNext() ;
        }
        HRdb.close();
        return info;
    }


    public void getData(){
        String name,surname,email,contact;

    //parse json data
        try {

               JSONArray jArray = new JSONArray(result);

               for(int i=0; i<jArray.length();i++){
                   JSONObject json = jArray.getJSONObject(i);
                   surname = json.getString("surname");
                   name = json.getString("name");
                   email = json.getString("email");
                   contact = json.getString("contact");

                   HRdb.execSQL("INSERT INTO HRinfotbl VALUES ('"+surname+"','"+name+"','"+email+"','"+contact+"');");
                   resultView.setText("Succesfully updated your database.");


               }


           } catch (Exception e) {
            // TODO: handle exception
               Log.e("log_tag", "Error Parsing Data "+e.toString());
           }


    }

private class httprRequest extends AsyncTask<String,Integer,String>{

        @Override
        public String doInBackground(String... params){
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            try
            {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("pvt");
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                if(response.getStatusLine().getStatusCode()!=200){
                    Log.d("MyApp", "Server encontered an error.");
                }
            HttpEntity entity = response.getEntity();
            isr = entity.getContent();
            }catch(Exception e){
                Log.e("log_entity", "Error in http connection: "+e.toString());
                }

            //conversion happening here..
        try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
            }
            isr.close();

            result = sb.toString();
    }
    catch(Exception e){
            Log.e("log_buf", "Error  converting result "+e.toString());
    }

        return result;

        }
    }
}

here is where I display most data.

public class Human_Resources extends MainActivity{
    TextView dbView;
    EditText searchtxt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.human_resources);

        dbView = (TextView) findViewById(R.id.showdb);
        searchtxt = (EditText) findViewById(R.id.searchtxt);
        dbView.setMovementMethod(new ScrollingMovementMethod());
        dbView.setText(SQLitePrint("HRinfotbl"));

        Button search = (Button) findViewById(R.id.searchbtn);
        search.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View v) 
        {
            dbView.setText(Search(searchtxt.getText().toString()));

        }
        });
    }



}

also I am very new to android, started last week. So just keep that in mind when giving an answer ;) thanks!

here is my error log. regarding when I try display for SQLite. db

01-15 08:47:16.856: W/ResourceType(7501): Failure getting entry for 0x01080a03 (t=7 e=2563) in package 0 (error -75)
01-15 08:47:16.876: E/log_entity(7501): Error in http connection: java.net.UnknownHostException: Unable to resolve host "www.deltabec.com": No address associated with hostname
01-15 08:47:16.876: E/log_buf(7501): Error  converting result java.lang.NullPointerException: lock == null
01-15 08:47:16.876: E/log_tag(7501): Error Parsing Data org.json.JSONException: End of input at character 0 of 
MrD
  • 95
  • 1
  • 9
  • What errors are you getting in LogCat? – Scary Wombat Jan 15 '14 at 06:38
  • You're apparently doing request inside the Activity onCreate. Make sure to fallback to sqlite completely when there is no internet. – Loïc Faure-Lacroix Jan 15 '14 at 06:41
  • @LoïcFaure-Lacroix hmm I may be missing what you saying, but as I see it on my human_resource I am calling functions from activity, where the SQLite db is created. also when it is created, no matte where, Does it not physically create a local db on the devices storage? – MrD Jan 15 '14 at 06:55

1 Answers1

1

The reason is that you are deleting the table in main activity without checking. The following lines are the problem for you. What is happening here is you delete the table data, when ever you start your app. So don't delete the table data blindly unless you dont have internet connection.

try {
        result = new httprRequest().execute().get();

        HRdb.delete("HRinfotbl", null, null);// This cause the problem.

    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

You can check for the internet if internet is avialable then delete and get the data otherwise dont delete the data so you might check here so you have to check here like

 try {
        result = new httprRequest().execute().get();
        // A work around to fix the problem
        if(internet avialable) {
            HRdb.delete("HRinfotbl", null, null);
        } else { 
            getData();
        }
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
  • My main activity is only called on a certain click. So if I update my DB then go to my viewing SQLite db. As long as I do not update again it should not delete the data... That is how I understand it. That problem I am trying to see to, just battling to check for internet in a simple manner. if you know of a way pls link. – MrD Jan 15 '14 at 06:52
  • Have a look at it. http://stackoverflow.com/questions/20989485/how-to-show-message-if-no-internet-available-in-my-android-webview/20989557#20989557 this is for check whether internet is avialable or not. Thanks –  Jan 15 '14 at 06:54
  • And if your main activity is called on certain click and you dont have internet connection. In that case the data will be deleted. –  Jan 15 '14 at 06:56
  • Thank you, that link was exactly what I needed for my connectivity issue. But still have the problem with when I open my local db it doesn't display from my local SQLite db the moment I loose internet... – MrD Jan 15 '14 at 07:00
  • Wow.. never mind.. it worked. haha thank you very much xD for everything, I can now view SQLite without internet ;) – MrD Jan 15 '14 at 07:12