I am developing a android application. I have used xampp server for making use of mysql.When i run the app it should sync with mysql and retreive values and store it in sqlite. I tries this example in the link http://ift.tt/ZYxP8Q . In the same way i developed the code,but in the example as in the link which i used has a column called syncsts in mysql to keep track of sync.But the problem is sync gets updated when one user uses the app and the status gets updated.Again if the other user uses the app then sync does not happens.
My doubt is
- I want to sync in such a way that when multiple user use the app sync between the mysql and sqlite should happen everytime and multiple users should access the app.How do i modify my code for that.
- I am using localhost here,problem is runs well with emulator but when tried with real device doesnt work.Only when the pc and mobile are in same network it works.I want to make multiple users use the app with different network.How do i do this.please help
My code is
MainActivity.java
public class MainActivity extends Activity implements OnClickListener
{
TextView update,updating;
Button btn1,btn2;
HashMap<String, String> queryValues;
DBController controller = new DBController(this);
@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<String> getAllUsers()
{
ArrayList<String> usersList;
usersList = new ArrayList<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 {
usersList.add(cursor.getString(0));
}while (cursor.moveToNext());
}
database.close();
return usersList;
}
public ArrayList<HashMap<String, String>> getUsers() {
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);
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put(cursor.getString(0), cursor.getString(1));
usersList.add(map);
} while (cursor.moveToNext());
}
database.close();
return usersList;
}
}
How do i achieve this.Please help with exaplanation
Aucun commentaire:
Enregistrer un commentaire