Java Sqlite和android应用程序arrayList
我一直在为一些产品开发应用程序。我在服务器和数据库中使用了xampp。我有三个活动MainActivity、HomeActivity和CategoryActivity。当我启动我的应用程序时,它将从mysql数据库检索数据并将其存储在sqlite数据库中。在CategoryActivity中,它将只检索类别列并显示Java Sqlite和android应用程序arrayList,java,android,mysql,sqlite,Java,Android,Mysql,Sqlite,我一直在为一些产品开发应用程序。我在服务器和数据库中使用了xampp。我有三个活动MainActivity、HomeActivity和CategoryActivity。当我启动我的应用程序时,它将从mysql数据库检索数据并将其存储在sqlite数据库中。在CategoryActivity中,它将只检索类别列并显示 当我更新mysql中的任何值时,我希望应用程序更新为新值,但旧值保持原样,新值也随之显示。我如何为此编写代码。旧值应替换为新值,新值必须显示 在CategoryActivity中,我
@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://192.168.1.104/website/getdbrowcount.php",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://192.168.1.104/website/getusers.php", 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://192.168.1.104/website/updatesyncsts.php", 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://192.168.1.104/website/getdbrowcount.php",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();
}
}
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();
}
}
}
@覆盖
创建时受保护的void(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1=(按钮)findViewById(R.id.button1);
btn2=(按钮)findViewById(R.id.button2);
update=(TextView)findViewById(R.id.update);
更新=(TextView)findViewById(R.id.updateding);
btn1.setOnClickListener(此);
btn2.setOnClickListener(此);
btn1.setEnabled(假);
btn1.setTextColor(Color.parseColor(#e0”);
updateing.setText(“更新最新sonetonix产品数据”);
update.setText(“连接到服务器,检查最新数据…”);
AsyncHttpClient=新的AsyncHttpClient();
RequestParams params=新的RequestParams();
客户邮寄(“http://192.168.1.104/website/getdbrowcount.php,参数,新的AsyncHttpResponseHandler(){
@凌驾
成功时公共无效(字符串响应)
{
System.out.println(响应);
尝试
{
日志d(“主页”、“成功”);
//从getdbrowcount.php发送的响应中创建JSON对象
JSONObject obj=新的JSONObject(响应);
Log.d(“home”,obj.toString());
System.out.println(对象获取(“计数”);
//如果计数值不为零,
如果(对象getInt(“计数”)!=0)
{
Log.d(“主页”,“计数不等于零”);
AlertDialog.Builder myalert=新建AlertDialog.Builder(MainActivity.this);
myalert.setTitle(“新产品数据可用”);
日志d(“主页”、“计数”);
myalert.setMessage(“新产品数据可用。是否要下载并更新?”);
myalert.setPositiveButton(“确定”,新的DialogInterface.OnClickListener()
{
@凌驾
公共void onClick(对话框接口对话框,int arg1)
{
//TODO自动生成的方法存根
//将数据从远程MySQL数据库传输到Android上的SQLite并执行同步
syncDB();
update.setText(“已开始同步到服务器”);
btn2.setVisibility(View.VISIBLE);
}
});
myalert.setNegativeButton(“取消”,新建DialogInterface.OnClickListener())
{
@凌驾
公共void onClick(对话框接口对话框,int arg1)
{
//TODO自动生成的方法存根
update.setText(“更新已被取消。请通过设置更新以正常工作”
+“最新Sonetonix产品数据”);
btn1.setEnabled(真);
btn1.setTextColor(Color.parseColor(#FFFFFF”);
btn2.setVisibility(视图已消失);
}
});
myalert.show();
}
其他的
{
Log.d(“home”,“count等于零”);
update.setText(“新产品不可用。请继续更新新产品…”);
btn1.setEnabled(真);
btn1.setTextColor(Color.parseColor(#FFFFFF”);
btn2.setVisibility(视图已消失);
}
}
捕获(JSONException e)
{
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}
public void onFailure(int状态码、可丢弃错误、字符串内容)
{
//TODO自动生成的方法存根
如果(状态代码==404)
{
update.setText(“更新已被取消。请通过设置更新以正常工作”
+“最新Sonetonix产品数据”);
Toast.makeText(getApplicationContext(),“未找到请求的资源”,Toast.LENGTH_LONG.show();
btn1.setEnabled(真);
btn1.setTextColor(Color.parseColor(#FFFFFF”);
}
否则如果(状态代码==500)
{
update.setText(“更新已被取消。请通过设置更新以正常工作”
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();
}
}
}