我想优化我的代码以减少应用程序的运行时间。目前,加载并显示欢迎屏幕需要18秒。
我正在使用AsyncTask来完成我的所有操作(JSON解析,数据库操作)。还有其他方法可以用来从我的应用程序中减少至少4秒。
我可以根据需要显示代码。请告诉我。
感谢你
我在这里分享了代码,请仔细阅读。
公共类MainActivity扩展了Activity {
/** THE FOLLOWING STRINGS WILL BE DISPLAYED IN LOGCAT */
final String TAG = "##--MAIN ACTIVITY--##";
UserHelper userAdapter;
Context context;
String regName="";
int duration = Toast.LENGTH_LONG;
String regNameSplit[];
JSONObject second_jsonObj = null;
JSONObject jsonObj = null;
JSONObject jsonobj = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
userAdapter = new UserHelper(this);
context = getApplicationContext();
final EditText edit_password = (EditText)findViewById(R.id.password);
final EditText edit_username = (EditText)findViewById(R.id.user_name);
final EditText edit_company = (EditText)findViewById(R.id.company_string);
final Button login = (Button)findViewById(R.id.login_button);
login.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
/*THE IF STATEMENT CHECKS IF THE FIELDS ARE EMPTY OR NOT*/
if (edit_username.getText().toString().equals("") || edit_username.getText().toString() == null ||
edit_password.getText().toString().equals("") || edit_password.getText().toString() == null||
edit_company.getText().toString().equals("") ||edit_company.getText().toString() == null ){
Log.i(TAG,"User has left some fields empty");
Toast.makeText(getApplicationContext(), "Enter all details", duration).show();
} else{
jsonobj = new JSONObject();
try{
//THE TRY STATEMENT CREATES A NEW JSON OBJECT TO BE PARSED IN HANDLEJSON METHOD//
JSONObject subJson = new JSONObject();
subJson.put("username", edit_username.getText().toString()/*"da"*/);
subJson.put("password", edit_password.getText().toString()/*"exicom"*/);
subJson.put("company", edit_company.getText().toString()/*"utb17"*/);
jsonobj.put("user", subJson);
Log.i(TAG,""+jsonobj);
}
catch(JSONException e) {
Log.i("","#####-----error at catch jsonexception-----#####");
}
//JSON OBJECT IS PARSED OVER HERE //
new synchronizeData(URL, jsonobj).execute();
}
}
});
}
class synchronizeData extends AsyncTask<Void, String, Void>{
private String name1;
private String company1;
private String password1;
private String regnaMe1;
private String reg1name1;
ProgressDialog PD ;
public synchronizeData(String name, String password, String company,
String regnaMe, String reg1name) {
// TODO Auto-generated constructor stub
this.name1 = name;
this.company1 = company;
this.password1 = password;
this.regnaMe1 = regnaMe;
this.reg1name1 = reg1name ;
}
public synchronizeData(String uRL, JSONObject jsonobj) {
// TODO Auto-generated constructor stub
}
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
Log.v(TAG,"Start of doInBackground");
try{
//Log.v(TAG,"The url is ********* "+URL);
//Log.v(TAG, "Json object request is "+jsonobj.toString());
DefaultHttpClient httpClientInstance = GetHttpClient.getHttpClientInstance();
HttpPost httpPostRequest = new HttpPost(URL);
Log.v(TAG,"The url is ********* "+URL);
StringEntity se;
se = new StringEntity(jsonobj.toString());
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");
long t = System.currentTimeMillis();
HttpResponse response = (HttpResponse) httpClientInstance.execute(httpPostRequest);
//Log.i(TAG, "HTTPRESPONSE RECIEVED in " +(System.currentTimeMillis()-t) + "ms");
String resultString = convertStreamToString(response.getEntity().getContent());
//Log.v(TAG ,/* "The response is "resultString);
jsonObj = new JSONObject(resultString);
JSONObject sessionJson = jsonObj.getJSONObject("session");
String sessionId = sessionJson.getString("sessionid");
String name = sessionJson.getString("name");
//Log.v(TAG,"The session ID is "+sessionId);
//Log.v(TAG,"The name is "+name);
regName = name+"-"+sessionId+"-"+URL;
} catch (JSONException e){
try{
Log.i(TAG,"JSON EXCEPTION FIRST");
JSONObject messageJson = jsonObj.getJSONObject("message");
String typeJson = messageJson.getString("type");
String contentJson = messageJson.getString("content");
regName = contentJson;
e.printStackTrace();
}catch(JSONException jse){
jse.printStackTrace();
}catch(Exception ee){
ee.printStackTrace();
}
}catch(Exception ee){
ee.printStackTrace();
}
Log.v(TAG,"before the return statement "+regName.toString());
//return regName;
try{
String regNameSplit[] = regName.split("-");
if(regNameSplit[0].equals("Invalid username or password")){
Toast.makeText(getApplicationContext(), ""+regNameSplit[0], duration).show();
}
else{
String regnaMe = regNameSplit[0].toString();
String reg1name = regNameSplit[1].toString();
Log.v(regnaMe,reg1name);
Intent intent = new Intent(MainActivity.this, Secondactivity.class);
intent.putExtra("regName", regNameSplit[0]);
intent.putExtra("regName_sessionID", regNameSplit[1]);
intent.putExtra("regName_URL", regNameSplit[2]);
startActivity(intent);
}
userAdapter.openDatabase();
//-------------THE DATABASE CHECKS IF THE VALUE IS PRESENT OR NOT IF TRUE DOESN'T INSERT-----------//
if(db.Exists(name1) == true){
} else {
long id = db.insertIntoDatabase(name1,company1,password1,regnaMe1,reg1name1);
Log.i(TAG, "Printing value of id which will be inserted only to remove warnings "+id);
}
}
catch(SQLiteException e){
e.printStackTrace();
}
return null;
}
private java.lang.String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try{
while((line = reader.readLine()) !=null ){
sb.append(line + "\n");
}
}
catch (IOException e){
e.printStackTrace();
} finally{
try {
is.close();
} catch (IOException e){
e.printStackTrace();
}
}
return sb.toString();
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
PD = new ProgressDialog(MainActivity.this);
PD.setMessage("Please wait....");
PD.show();
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
PD.dismiss();
userAdapter.closeDatabase();
}
}
}
这是第二项活动的代码:
String ht =“”; public final String TAG =“### --- Secondactivity --- ###”; public String reg_name =“”; public String resultString =“”;
// AccessTimeReportTableHelper dB;
JSONObject jsonobj = null;
Vector objVector = new Vector();
String bufferedValue = "";
String newdeletedtrsArray = "";
String newschemaArray = "";
String newtrsArray = "";
String URL_ = "";
AccessTimeReportTableHelper useradapter_TimeReportTable;
AccessMessageTable useradapterMessageTable;
AccessMessageTypeTable useradapterMessageTypeTable;
UserHelper userHelper;
AccessTimeReportMessage useradapterTimeReportMessage;
String[] split_newdeletedtrsArray;
String[] split_newschemaArray;
String[] split_newtrsArray;
String[] splitno1_split_newtrsArray;
ArrayList<GetSetMethod> bulk = new ArrayList<GetSetMethod>();
ProgressDialog PD;
@SuppressWarnings({ "rawtypes", "unused" })
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondactivity);
Log.v(TAG, "Start of second activity");
userHelper = new UserHelper(this);
useradapterMessageTable = new AccessMessageTable(this);
useradapter_TimeReportTable = new AccessTimeReportTableHelper(this);
useradapterMessageTypeTable = new AccessMessageTypeTable(this);
useradapterTimeReportMessage = new AccessTimeReportMessage(this);
if (getIntent().getStringExtra("regName") != null) {
try {
String name = getIntent().getStringExtra("regName");
String session_ID = getIntent().getStringExtra(
"regName_sessionID");
URL_ = "URL inserted here";
jsonobj = new JSONObject("custom JSON OBJECT HERE");
String ht = URL_ + "&" + jsonobj;
// Log.i("" + ht, "");
JSONObject jsonObj = null;
String resultString = "";
String deletedtrsArray = "";
String newtrsArray = "";
String newschemaArray = "";
String bufferedValue = "";
Log.v(TAG, "The url is " + URL_);
Log.v(TAG, "Json object request is " + jsonobj.toString());
new AsyncSecondActivity(jsonobj).execute();
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception en) {
en.printStackTrace();
}
}
Log.v(TAG, "Ending program execution here");
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
class AsyncSecondActivity extends AsyncTask<Void, String, Void> {
private String newcompanyid1;
private String newdate1;
private String newusername1;
private String newClientId1;
private String newprojectId1;
private String newniV1;
private String newniV2;
private String newworktypeid1;
private String newtimetypeid1;
private String newhours1;
private String newcomment1;
private String newprivatecomment1;
private String newopen1;
private String newreportid1;
String messageTypeId = "";
String messageConcat = "";
String concatCursorCompare = "";
String newcompanyid;
String date_id = "";
String compareId = "";
String newusername = "";
String newdate = "";
String newClientId = "";
String newprojectId = "";
String newniv1 = "";
String newniv2 = "";
String newworktypeid = "";
String newtimetypeid = "";
String newhours = "";
String newcomment = "";
String newprivatecomment = "";
String newopen = "";
String newreportid = "";
String dateId = "";
String messageType_System = "";
String message_content = "";
String userId_FirstActivity = "";
String date = "";
String report = "";
// Cursor DECLARATION//
Cursor c = null;
Cursor cur = null;
Cursor curMessageTable = null;
Cursor curMessageName = null;
Cursor curMainActivity = null;
Cursor curTimeReportMessage = null;
public AsyncSecondActivity(JSONObject jsonobj) {
Log.v(TAG, "Value of BULK in AsyncSecondActivity (GETSET METHOD) "
+ jsonobj);
}
@Override
protected Void doInBackground(Void... params) {
try{
DefaultHttpClient httpClientInstance = GetHttpClient
.getHttpClientInstance();
HttpPost httpPostRequest = new HttpPost(URL_);
Log.v(TAG, "The url is " + URL_);
StringEntity se;
se = new StringEntity(jsonobj.toString());
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");
long t = System.currentTimeMillis();
HttpResponse response = (HttpResponse) httpClientInstance
.execute(httpPostRequest);
Log.i(TAG,
"HTTPRESPONSE RECIEVED in "
+ (System.currentTimeMillis() - t) + "ms");
resultString = convertStreamToString(response.getEntity()
.getContent());
// Log.v(TAG , "The response is " +resultString);
jsonobj = new JSONObject(resultString);
JSONObject sync_reponse = jsonobj.getJSONObject("syncresponse");
String synckey_string = sync_reponse.getString("synckey");
JSONArray createdtrs_array = sync_reponse
.getJSONArray("createdtrs");
JSONArray modtrs_array = sync_reponse.getJSONArray("modtrs");
// -----HANDLING MODTRS-----//
for (int n = 0; n < modtrs_array.length(); n++) {
JSONObject object = modtrs_array.getJSONObject(n);
String newcompanyID_mod = object.getString("companyid");
String newusername_mod = object.getString("username");
String newdate_mod = object.getString("date");
String newclientid_mod = object.getString("clientid");
String newprojectid_mod = object.getString("projectid");
String newniv1_mod = object.getString("niv1");
String newniv2_mod = object.getString("niv2");
String newworktypeid_mod = object.getString("worktypeid");
String newtimetypeid_mod = object.getString("timetypeid");
String newhours_mod = object.getString("hours");
String newcomment_mod = object.getString("comment");
String newprivatecomment_mod = object
.getString("privatecomment");
String newopen_mod = object.getString("open");
if ((object.has("message"))) {
JSONObject messaget = object.getJSONObject("message");
String newtype = object.getJSONObject("message")
.getString("type");
String newcontent = object.getJSONObject("message")
.getString("content");
GetSetMethod objSample = new GetSetMethod();
objSample.setnewclientid_mod(newclientid_mod);
objSample.setnewusername_mod(newusername_mod);
objSample.setnewdate_mod(newdate_mod);
objSample.setnewprojectid_mod(newprojectid_mod);
objSample.setNewniv1(newniv1_mod);
objSample.setNewniv2(newniv2_mod);
objSample.setNewworktypeid(newworktypeid_mod);
objSample.setNewtimetypeid(newtimetypeid_mod);
objSample.setNewhours(newhours_mod);
objSample.setNewcomment(newcomment_mod);
objSample.setNewopen(newopen_mod);
objSample.setNewprivatecomment(newprivatecomment_mod);
}
}
JSONArray deletedtrs_array = sync_reponse
.getJSONArray("deletedtrs");
// -----------------------HANDLING
// DELETEDTRS------------------------//
for (int n = 0; n < deletedtrs_array.length(); n++) {
JSONObject object = deletedtrs_array.getJSONObject(n);
String newUserName = object.getString("username");
String newCompanyId = object.getString("companyid");
String newDate = object.getString("date");
String newReportId = object.getString("reportid");
}
JSONArray newtrs_array = sync_reponse.getJSONArray("newtrs");
// -----------------------HANDLING
// NEWTRS----------------------------//
GetSetMethod objSample = null;
for (int n = 0; n < newtrs_array.length(); n++) {
JSONObject object = newtrs_array.getJSONObject(n);
String newcompanyid = object.getString("companyid");
String newusername = object.getString("username");
String newdate = object.getString("date");
String newClientId = object.getString("clientid");
String newprojectId = object.getString("projectid");
String newniv1 = object.getString("niv1");
String newniv2 = object.getString("niv2");
String newworktypeid = object.getString("worktypeid");
String newtimetypeid = object.getString("timetypeid");
String newhours = object.getString("hours");
String newcomment = object.getString("comment");
String newprivatecomment = object
.getString("privatecomment");
String newopen = object.getString("open");
String newreportid = object.getString("reportid");
String newcontent_mod = "";
String newtype_mod = "";
if ((object.has("message"))) {
JSONObject message = object.getJSONObject("message");
newtype_mod = object.getJSONObject("message")
.getString("type");
newcontent_mod = object.getJSONObject("message")
.getString("content");
// objSample = new GetSetMethod();
// objSample.setnewcontent_mod(newcontent_mod);
// objSample.setnewtype_mod(newtype_mod);
}
objSample = new GetSetMethod();
objSample.setNewcompanyid(newcompanyid);
objSample.setNewusername(newusername);
objSample.setNewdate(newdate);
objSample.setNewClientId(newClientId);
objSample.setNewprojectId(newprojectId);
objSample.setNewniv1(newniv1);
objSample.setNewniv2(newniv2);
objSample.setNewworktypeid(newworktypeid);
objSample.setNewtimetypeid(newtimetypeid);
objSample.setNewhours(newhours);
objSample.setNewcomment(newcomment);
objSample.setNewprivatecomment(newprivatecomment);
objSample.setNewopen(newopen);
objSample.setNewreportid(newreportid);
if ((newcontent_mod) != null || (newtype_mod) != null) {
objSample.setnewcontent_mod(newcontent_mod);
objSample.setnewtype_mod(newtype_mod);
}
bulk.add(objSample);
objSample.getNewClientId();
for (int i = 0; i < objVector.size(); i++) {
GetSetMethod objtest = new GetSetMethod();
objtest = (GetSetMethod) objVector.get(i);
objtest.getNewClientId();
objtest.getNewcompanyid();
}
}
//new AsyncSecondActivity(bulk).execute();
// -----------------------HANDLING
// SCHEMA-------------------------//
JSONArray schema_array = sync_reponse.getJSONArray("schema");
for (int n = 0; n < schema_array.length(); n++) {
JSONObject object = schema_array.getJSONObject(n);
String new_yearmonth = object.getString("yearmonth");
String new_hoursperday = object.getString("hoursperday");
}
} catch(JSONException e){
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HashMap<String, String> recordExist = new HashMap<String, String>();
userHelper.openDatabase();
useradapter_TimeReportTable.openDatabase();
useradapterMessageTable.openDatabase();
useradapterMessageTypeTable.openDatabase();
useradapterTimeReportMessage.openDatabase();
curMainActivity = userHelper.retrieveUserId();
cur = useradapter_TimeReportTable.getUniqueRecordsId();
curMessageTable = useradapterMessageTable.getMessageTable();
curMessageName = useradapterMessageTypeTable.getMessageTypeId();
for (int i = 0; i < bulk.size(); i++) {
GetSetMethod objtest = bulk.get(i);
this.newcompanyid1 = objtest.getNewcompanyid();
this.newusername1 = objtest.getNewusername();
this.newworktypeid1 = objtest.getNewworktypeid();
this.newniV2 = objtest.getNewniv2();
this.newniV1 = objtest.getNewniv1();
this.newdate1 = objtest.getNewdate();
this.newClientId1 = objtest.getNewClientId();
this.newprojectId1 = objtest.getNewprojectId();
this.newtimetypeid1 = objtest.getNewtimetypeid();
this.newhours1 = objtest.getNewhours();
this.newcomment1 = objtest.getNewcomment();
this.newprivatecomment1 = objtest.getNewprivatecomment();
this.newopen1 = objtest.getNewopen();
this.newreportid1 = objtest.getNewreportid();
this.message_content = objtest.getnewcontent_mod();
this.messageType_System = objtest.getnewtype_mod();
concatCursorCompare = date + "-" + report;
//Log.v("Line number 408: SecondActivity", "Value: " + date);
//Log.v("Line number 409: SecondActivity", "Value: " + report);
recordExist.put(concatCursorCompare, concatCursorCompare);
compareId = objtest.getNewdate() + "-"
+ objtest.getNewreportid();
if (!recordExist.containsValue(compareId)) {
long id = useradapter_TimeReportTable
.insertIntoDatabase(newcompanyid1,
newusername1, newdate1, newClientId1,
newprojectId1, newniV1, newniV2,
newworktypeid1, newtimetypeid1,
newhours1, newcomment1,
newprivatecomment1, newopen1,
newreportid1, userId_FirstActivity);
}
if (cur.moveToFirst()) {
do {
date = cur.getString(cur.getColumnIndexOrThrow("dateId"));
report = cur.getString(cur.getColumnIndexOrThrow("reportId"));
}
while(cur.moveToNext());
}
if (curMessageName.moveToFirst()) {
messageTypeId = curMessageName.getString(curMessageName
.getColumnIndex("messageTypeId"));
}
else {
if (messageType_System != null && messageType_System != "") {
long ins_msg_typ_tbl = useradapterMessageTypeTable
.insertintoMessageTypeName(messageType_System);
curMessageName = useradapterMessageTypeTable.recordExistsmessageTypeTable(messageType_System);
if (curMessageName.moveToFirst()) {
messageTypeId = curMessageName.getString(curMessageName
.getColumnIndex("messageTypeId"));
}
}
}
if (curMainActivity.moveToFirst()) {
userId_FirstActivity = curMainActivity
.getString(curMainActivity
.getColumnIndexOrThrow("userId"));
}
concatCursorCompare = date + "-" + report;
Log.v("Line number 408: SecondActivity", "Value: " + date);
Log.v("Line number 409: SecondActivity", "Value: " + report);
recordExist.put(concatCursorCompare, concatCursorCompare);
compareId = objtest.getNewdate() + "-"
+ objtest.getNewreportid();
}
for (int i = 0; i < bulk.size(); i++) {
GetSetMethod objtest = bulk.get(i);
this.newcompanyid1 = objtest.getNewcompanyid();
this.newusername1 = objtest.getNewusername();
this.newworktypeid1 = objtest.getNewworktypeid();
this.newniV2 = objtest.getNewniv2();
this.newniV1 = objtest.getNewniv1();
this.newdate1 = objtest.getNewdate();
this.newClientId1 = objtest.getNewClientId();
this.newprojectId1 = objtest.getNewprojectId();
this.newtimetypeid1 = objtest.getNewtimetypeid();
this.newhours1 = objtest.getNewhours();
this.newcomment1 = objtest.getNewcomment();
this.newprivatecomment1 = objtest.getNewprivatecomment();
this.newopen1 = objtest.getNewopen();
this.newreportid1 = objtest.getNewreportid();
this.message_content = objtest.getnewcontent_mod();
this.messageType_System = objtest.getnewtype_mod();
try {
compareId = objtest.getNewdate() + "-"
+ objtest.getNewreportid();
if(message_content != null && message_content !=""){
long insertMessageTable = useradapterMessageTable.insertintoMessageTable(messageTypeId,message_content);
}
if(message_content != null && message_content !="" && report!=null && report != ""){
long insertTimeReportMessage = useradapterTimeReportMessage.insertintoTimeReportMessgeTable(report, messageTypeId, date);
}
}catch (Exception e) {
e.printStackTrace();
} finally {
if (curMainActivity != null) {
curMainActivity.close();
curMainActivity = null;
}
if (c != null) {
c.close();
c = null;
}
if (cur != null) {
cur.close();
cur = null;
}
if (curMessageTable != null) {
curMessageTable.close();
curMessageTable = null;
}
if (curMessageName != null) {
curMessageName.close();
curMessageName = null;
}
if(curTimeReportMessage != null){
curTimeReportMessage.close();
curTimeReportMessage = null;
}
}
}
return null;
}
@Override
protected void onPostExecute(Void result) throws SQLiteException {
super.onPostExecute(result);
PD.dismiss();
userHelper.closeDatabase();
useradapter_TimeReportTable.closeDatabase();
useradapterMessageTable.closeDatabase();
useradapterMessageTypeTable.closeDatabase();
useradapterTimeReportMessage.closeDatabase();
Toast.makeText(getApplicationContext(),
"Welcome " + getIntent().getStringExtra("regName"),
Toast.LENGTH_LONG).show();
}
@Override
protected void onPreExecute() {
super.onPreExecute();
try {
PD = new ProgressDialog(Secondactivity.this);
PD.setTitle("Please wait");
PD.setMessage("Updating records");
PD.show();
} catch (Exception progressDialog) {
progressDialog.printStackTrace();
}
}
}
}
简单来说,我会使用用户名密码并将其插入数据库。从webservice获得JSON响应后(通过发送用户名和密码获得)我将JSON对象解析为字符串,然后将其插入数据库。
在第二个活动中,我获取了一个JSON响应,我将其解析并将输入转换为字符串。然后,我将JSON响应插入到各自的数据库中。
答案 0 :(得分:0)
模拟器很慢 - 正常的设备可能会很快。延迟的一个潜在来源是UserHelper对象创建 - 您没有提供它的源代码。您还省略了活动的onResume()方法的代码。找到性能的最佳方法是使用ddms执行性能分析。