mercredi 15 juillet 2015

Sqlite and android app arrayList

I have been developing an application for some of the products.I have used xampp for the server and database.I have three activities MainActivity,HomeActivity and CategoryActivity.When i start my app,it will retrieve the data from mysql database and store it in sqlite database. In CategoryActivity it will retrieve only the category column and display.I have come across with two problems.

  1. When i update any value in mysql then i want the app to get updated with new values but the older value is remaining as it is and along with the new value is also getting displayed.how do i write the code for this.The older one should be replaced with new value and new value has to display.

  2. In CategoryActivity i want to go to subcategoryActivity only if a category has a subcategory else it should display directly productsActivity[if subcategory is null then go to productsActivity directly else go to SubcategoryAcitivity.How do i code for this.

MainActivity.java

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

     btn1=(Button) findViewById(R.id.button1);
     btn2=(Button) findViewById(R.id.button2);
     update=(TextView) findViewById(R.id.update);
     updating=(TextView) findViewById(R.id.updating);


     btn1.setOnClickListener(this);      
     btn2.setOnClickListener(this);
     btn1.setEnabled(false);
     btn1.setTextColor(Color.parseColor("#E0E0E0"));

     updating.setText("Updating the latest sonetonix product data");
     update.setText("Connecting to server, checking latest data..");


     AsyncHttpClient client = new AsyncHttpClient();
     RequestParams params = new RequestParams();

     client.post("http://ift.tt/1TDR12f",params ,new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(String response) 
            {
                System.out.println(response);
                try
                {                 
                    Log.d("home", "success");
                     // Create JSON object out of the response sent by getdbrowcount.php
                    JSONObject obj = new JSONObject(response);
                    Log.d("home", obj.toString());
                    System.out.println(obj.get("count"));           
                    // If the count value is not zero, 
                    if(obj.getInt("count") != 0)
                    {
                        Log.d("home", "count not equal to zero");
                        AlertDialog.Builder myalert=new AlertDialog.Builder(MainActivity.this);
                        myalert.setTitle("New product data available");
                        Log.d("home", "count");
                        myalert.setMessage("New product data is available.Would you like to download and update?");
                        myalert.setPositiveButton("ok", new DialogInterface.OnClickListener() 
                        {

                            @Override
                            public void onClick(DialogInterface dialog, int arg1)
                            {
                                // TODO Auto-generated method stub

                                // Transfer data from remote MySQL DB to SQLite on Android and perform Sync
                                 syncDB();
                                 update.setText("Started syncing to server");
                                 btn2.setVisibility(View.VISIBLE);
                            }
                        }); 


                        myalert.setNegativeButton("cancel", new DialogInterface.OnClickListener() 
                        {

                            @Override
                            public void onClick(DialogInterface dialog, int arg1) 
                            {
                                // TODO Auto-generated method stub                               
                                 update.setText("The update has been cancelled. Please update via Settings to work"
                                        + " with latest Sonetonix product data");
                                 btn1.setEnabled(true);
                                 btn1.setTextColor(Color.parseColor("#FFFFFF"));
                                 btn2.setVisibility(View.GONE);

                            }
                        });
                        myalert.show();
                    }
                    else
                    { 
                        Log.d("home", "count is equal to zero"); 
                        update.setText("New Products are not available. Please keep updating for the new products..");
                        btn1.setEnabled(true);
                        btn1.setTextColor(Color.parseColor("#FFFFFF"));
                        btn2.setVisibility(View.GONE);
                    }

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

            public void onFailure(int statusCode, Throwable error,String content) 
            {
                    // TODO Auto-generated method stub
                    if(statusCode == 404)
                    {
                        update.setText("The update has been cancelled. Please update via Settings to work"
                                + " with latest Sonetonix product data");
                        Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
                        btn1.setEnabled(true);
                        btn1.setTextColor(Color.parseColor("#FFFFFF"));
                    }
                    else if(statusCode == 500)
                    {
                        update.setText("The update has been cancelled. Please update via Settings to work"
                                + " with latest Sonetonix product data");
                        Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
                        btn1.setEnabled(true);
                        btn1.setTextColor(Color.parseColor("#FFFFFF"));
                    }
                    else
                    {
                        update.setText("The update has been cancelled. Please update via Settings to work"
                                + " with latest Sonetonix product data");
                        Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]", Toast.LENGTH_LONG).show();
                        btn1.setEnabled(true);
                        btn1.setTextColor(Color.parseColor("#FFFFFF"));
                    }
             }

      });

}

public void  syncDB()
{
    Log.d("home", "db sync");

    // Create AsycHttpClient object
    AsyncHttpClient client = new AsyncHttpClient();
 // Http Request Params Object
    RequestParams params = new RequestParams();

    client.post("http://ift.tt/1TDQZaS", params, new AsyncHttpResponseHandler() 
    {
        @Override

      public void onSuccess(String response)

        {

            // Update SQLite DB with response sent by getusers.php
            updatesqlite(response);
        }



        // When error occured
        @Override
        public void onFailure(int statusCode, Throwable error, String content) 
        {
            // TODO Auto-generated method stub             
            if (statusCode == 404)
            {
                update.setText("The update has been cancelled. Please update via Settings to work"
                        + " with latest Sonetonix product data");
                Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
                btn1.setEnabled(true);
                btn1.setTextColor(Color.parseColor("#FFFFFF"));
                btn2.setVisibility(View.GONE);
            } 
            else if (statusCode == 500) 
            {
                update.setText("The update has been cancelled. Please update via Settings to work"
                        + " with latest Sonetonix product data");
                Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
                btn1.setEnabled(true);
                btn1.setTextColor(Color.parseColor("#FFFFFF"));
                btn2.setVisibility(View.GONE);
            }
            else
            {
                update.setText("The update has been cancelled. Please update via Settings to work"
                        + " with latest Sonetonix product data");
                Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]", Toast.LENGTH_LONG).show();
                btn1.setEnabled(true);
                btn1.setTextColor(Color.parseColor("#FFFFFF"));
                btn2.setVisibility(View.GONE);
            }
        } 
   }); 

}

public void  updatesqlite(String response)
{

    Log.d("home",response);
    ArrayList<HashMap<String, String>> usersynclist;
    usersynclist = new ArrayList<HashMap<String, String>>();


    // Create GSON object
    Gson gson = new GsonBuilder().create();
    try
    {
        // Extract JSON array from the response
        JSONArray arr = new JSONArray(response);
        System.out.println(arr.length());
     // If no of array elements is not zero
        if(arr.length() != 0)
        {            
            for (int i = 0; i < arr.length(); i++) 
            {
                // Get JSON object
                JSONObject obj = (JSONObject) arr.get(i);
                System.out.println(obj.get("productId"));
                System.out.println(obj.get("category"));
                System.out.println(obj.get("subcategory"));
                System.out.println(obj.get("mountingstyle"));
                System.out.println(obj.get("products"));
                System.out.println(obj.get("description"));

             // DB QueryValues Object to insert into SQLite
                queryValues = new HashMap<String, String>();
                queryValues.put("productId", obj.get("productId").toString());
                queryValues.put("category", obj.get("category").toString());
                queryValues.put("subcategory", obj.get("subcategory").toString());
                queryValues.put("mountingstyle", obj.get("mountingstyle").toString());
                queryValues.put("products", obj.get("products").toString());
                queryValues.put("description", obj.get("description").toString());

                // Insert User into SQLite DB
                controller.insertUser(queryValues);

                Log.d("home","inserted properly");

                HashMap<String, String> map = new HashMap<String, String>();
                // Add status for each User in Hashmap
                Log.d("home",map.toString());

                map.put("products", obj.get("products").toString());
                map.put("status", "1"); 
                usersynclist.add(map);

                System.out.println("---------------------------------------------" + usersynclist); 
                Log.d("home",map.toString());
                Handler handler = new Handler();
                handler.postDelayed(new Runnable()
                {
                      @Override
                      public void run() 
                      {
                        //Do something after 100ms

                      }
                    }, 4000);
            }

         // Inform Remote MySQL DB about the completion of Sync activity by passing Sync status of Users
            updatesyncsts(gson.toJson(usersynclist));

         // Reload the Main Activity
            reloadActivity();
        } 

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


// Method to inform remote MySQL DB about completion of Sync activity
public void updatesyncsts(String json)
{

     System.out.println(json);
     AsyncHttpClient client = new AsyncHttpClient();
     RequestParams params = new RequestParams();
     params.put("syncsts", json);
     System.out.println(params);
     // Make Http call to updatesyncsts.php with JSON parameter which has Sync statuses of Users
        client.post("http://ift.tt/1TDQZr6", params, new AsyncHttpResponseHandler()
        {
            @Override
            public void onSuccess(String response)
            {
                Log.d("home",response);
                btn2.setVisibility(View.GONE);
                btn1.setEnabled(true);
                btn1.setTextColor(Color.parseColor("#FFFFFF"));
            }  

            @Override
            public void onFailure(int statusCode, Throwable error, String content)
            {
                 if (statusCode == 404)
                 {
                    update.setText("The update has been cancelled. Please update via Settings to work"
                            + " with latest Sonetonix product data");
                     Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
                     btn1.setEnabled(true);
                     btn1.setTextColor(Color.parseColor("#FFFFFF"));
                     btn2.setVisibility(View.GONE);
                 } 
                 else if (statusCode == 500) 
                 {
                    update.setText("The update has been cancelled. Please update via Settings to work"
                            + " with latest Sonetonix product data");
                     Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
                     btn1.setEnabled(true);
                     btn1.setTextColor(Color.parseColor("#FFFFFF"));
                     btn2.setVisibility(View.GONE);
                 }
                 else
                 {
                    update.setText("The update has been cancelled. Please update via Settings to work"
                            + " with latest Sonetonix product data");
                     Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]", Toast.LENGTH_LONG).show();
                     btn1.setEnabled(true);
                     btn1.setTextColor(Color.parseColor("#FFFFFF"));
                     btn2.setVisibility(View.GONE);
                 }               
            }

      });
 }

// Reload MainActivity
public void reloadActivity()
{
    Intent objIntent = new Intent(getApplicationContext(), MainActivity.class);
    startActivity(objIntent);
    update.setText("Updated successfully");
}

@Override
public void onClick(View v)
{
    // TODO Auto-generated method stub
    if(v.getId()==R.id.button1)
    {
        Intent intent=new Intent(MainActivity.this,HomeActivity.class);
        startActivity(intent);
    }

    if(v.getId()==R.id.button2)
    {
        Log.d("home","clicked");        
        AlertDialog.Builder myalert=new AlertDialog.Builder(MainActivity.this);
        myalert.setTitle("Abort update process");
        myalert.setMessage("Are you sure you want to stop the update process?");
        myalert.setPositiveButton("ok", new DialogInterface.OnClickListener() 
        {

            @Override
            public void onClick(DialogInterface dialog, int arg1)
            {
                // TODO Auto-generated method stub
                Log.d("home","ok");
                update.setText("Please wait... Saving the necessary files before aborting update process...");                  
                Handler handler = new Handler();
                handler.postDelayed(new Runnable()
                {
                      @Override
                      public void run() 
                      {
                        //Do something after 100ms
                          update.setText("The update has been cancelled. Please update via Settings to work"
                                + " with latest Sonetonix product data"); 
                          btn1.setEnabled(true);
                          btn1.setTextColor(Color.parseColor("#FFFFFF"));
                          btn2.setVisibility(View.GONE);
                      }
                    }, 5000);

            }
        });


        myalert.setNegativeButton("cancel", new DialogInterface.OnClickListener() 
        {

            @Override
            public void onClick(DialogInterface dialog, int arg1) 
            {
                // TODO Auto-generated method stub
                 AsyncHttpClient client = new AsyncHttpClient();
                 RequestParams params = new RequestParams();

                 client.post("http://ift.tt/1TDR12f",params ,new AsyncHttpResponseHandler() {
                        @Override
                        public void onSuccess(String response) 
                        {
                             System.out.println(response);
                                try
                                {                 
                                    Log.d("home", "success");
                                     // Create JSON object out of the response sent by getdbrowcount.php
                                    JSONObject obj = new JSONObject(response);
                                    Log.d("home", obj.toString());
                                    System.out.println(obj.get("count"));           
                                    // If the count value is not zero, 
                                    if(obj.getInt("count") != 0)
                                    {

                                        syncDB();
                                        update.setText("Started syncing to server");                                                                                    

                                    }
                                    else
                                    { 
                                        Log.d("home", "count is equal to zero"); 
                                        update.setText("New Products are not available. Please keep updating for the new products..");
                                        btn1.setEnabled(true);
                                        btn1.setTextColor(Color.parseColor("#FFFFFF"));
                                        btn2.setVisibility(View.GONE);
                                    }
                                }
                                catch (JSONException e) 
                                {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                                }
                            }

                            public void onFailure(int statusCode, Throwable error,String content) 
                            {
                                    // TODO Auto-generated method stub
                                    if(statusCode == 404)
                                    {
                                        update.setText("The update has been cancelled. Please update via Settings to work"
                                                + " with latest Sonetonix product data");
                                        Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
                                        btn1.setEnabled(true);
                                        btn1.setTextColor(Color.parseColor("#FFFFFF"));
                                    }
                                    else if(statusCode == 500)
                                    {
                                        update.setText("The update has been cancelled. Please update via Settings to work"
                                                + " with latest Sonetonix product data");
                                        Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
                                        btn1.setEnabled(true);
                                        btn1.setTextColor(Color.parseColor("#FFFFFF"));
                                    }
                                    else
                                    {
                                        update.setText("The update has been cancelled. Please update via Settings to work"
                                                + " with latest Sonetonix product data");
                                        Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]", Toast.LENGTH_LONG).show();
                                        btn1.setEnabled(true);
                                        btn1.setTextColor(Color.parseColor("#FFFFFF"));
                                    }
                             }

                      });

                }

        });

      myalert.show();

    }
}

DBController.java

public class DBController extends SQLiteOpenHelper
 {
   private static final String DATABASE_NAME = "SonetonixProducts.db";
   private static final int DATABASE_VERSION = 1;


public DBController(Context context)
{
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    Log.d("home",DATABASE_NAME);

}

@Override 
public void onCreate(SQLiteDatabase database) 
{

    String query;
    query="CREATE TABLE guide (slno INTEGER PRIMARY KEY AUTOINCREMENT, productId INTEGER, category TEXT, subcategory TEXT, mountingstyle TEXT, products TEXT, description TEXT )";
    // TODO Auto-generated method stub
     database.execSQL(query);
     Log.d("home","table created");
}

@Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion)
{
    // TODO Auto-generated method stub
    String query;
    query= "DROP TABLE IF EXISTS guide";
    database.execSQL(query);
    onCreate(database);
}

public void insertUser(HashMap<String, String> queryValues) 

    {
        SQLiteDatabase database = this.getWritableDatabase();
        Log.d("home",database.toString());
        ContentValues values = new ContentValues();

        values.put("productId", queryValues.get("productId"));
        values.put("category", queryValues.get("category"));
        values.put("subcategory", queryValues.get("subcategory"));
        values.put("mountingstyle", queryValues.get("mountingstyle"));
        values.put("products", queryValues.get("products"));
        values.put("description", queryValues.get("description"));
        database.insert("guide", null, values);
        database.close(); 
        Log.d("home","inserted");
    }

 public ArrayList<HashMap<String, String>> getAllUsers() 
  {
   ArrayList<HashMap<String, String>> usersList;
   usersList = new ArrayList<HashMap<String, String>>();
   String selectQuery = "SELECT category,subcategory FROM guide";
   SQLiteDatabase database = this.getWritableDatabase();
   Cursor cursor = database.rawQuery(selectQuery, null);
   Log.d("home", cursor.toString());
   if (cursor.moveToFirst()) {
       do {


           HashMap<String, String> map = new HashMap<String, String>();


           map.put("category", cursor.getString(0));       
           map.put("subcategory", cursor.getString(1));
           usersList.add(map);

           Log.d("home",usersList.toString());
       }while (cursor.moveToNext());
   }
   database.close();
   return usersList;
 }
}

categoryActivity.java

public class CategoryActivity extends Activity implements OnClickListener
{

Button tab1,tab2,tab3,tab4,cbackbtn;
DBController controller = new DBController(this);

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_category);

    tab1=(Button) findViewById(R.id.cctab1);
    tab2=(Button) findViewById(R.id.cctab2);
    tab3=(Button) findViewById(R.id.cctab3);
    tab4=(Button) findViewById(R.id.cctab4);
    cbackbtn=(Button) findViewById(R.id.cbackbtn);

    tab1.setOnClickListener(this);
    tab2.setOnClickListener(this);
    tab3.setOnClickListener(this);
    tab4.setOnClickListener(this);
    cbackbtn.setOnClickListener(this);

    ArrayList<HashMap<String, String>> userList = controller.getAllUsers();

    // If users exists in SQLite DB
    if (userList.size() != 0)
    {
        // Set the User Array list in ListView


    ListAdapter adapter = new SimpleAdapter(CategoryActivity.this, userList, R.layout.listview, new String[] {
                 "category" }, new int[] { R.id.category});
    ListView list = (ListView) findViewById(R.id.listView1);
    list.setAdapter(adapter);        
    registercallback();
    }

}

private void registercallback()
{
      ListView list = (ListView) findViewById(R.id.listView1);
      list.setOnItemClickListener(new OnItemClickListener()
      {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) 
        {
            // TODO Auto-generated method stub




        }

     });




}


@Override
public void onClick(View v)
{
    // TODO Auto-generated method stub
    if(v.getId()==R.id.cctab1)
    {
        Intent home=new Intent(CategoryActivity.this,HomeActivity.class);
        startActivity(home);
    }

    if(v.getId()==R.id.cctab2)
    {
        Intent home=new Intent(CategoryActivity.this,HomeActivity.class);
        startActivity(home);
    }

    if(v.getId()==R.id.cctab3)
    {
        Intent home=new Intent(CategoryActivity.this,HomeActivity.class);
        startActivity(home);
    }

    if(v.getId()==R.id.cctab4)
    {
        Intent home=new Intent(CategoryActivity.this,HomeActivity.class);
        startActivity(home);
    }
    if(v.getId()==R.id.cbackbtn)
    {
        finish();
    }

    }

}

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire