-1

我有一个名为 global 的类,它扩展了 Application,以维护在第一个活动中获得的值到下一个活动,我通过使用 getter 和 setter 函数来使用这个类。每当我想从当前活动中获取或设置任何值时,我都会创建一个全局类的静态对象。应用程序将在第一次启动和半小时后正常运行。如果我想在半小时后恢复应用程序,则全局类中贴花的所有变量都变为空,并且恢复活动的变量也变为空。

我确信我的代码中存在一些问题。我请求任何人帮助我摆脱这个错误。

请在此处查看我的代码 package com.globalnest;

导入android.app.Application;

公共类 GlobalClass 扩展应用程序 { public int displayTab = 0;

public int getDisplayTab() {
    return displayTab;
}

public void setDisplayTab(int displayTab) {
    this.displayTab = displayTab;
}

public boolean isLeaddetails;

public boolean isLeaddetails() {
    return isLeaddetails;
}

public void setLeaddetails(boolean isLeaddetails) {
    this.isLeaddetails = isLeaddetails;
}

public static boolean startedApp;

public boolean isStartedApp() {
    return startedApp;
}

public void setStartedApp(boolean startedApp1) {
    startedApp = startedApp1;
}

public String accessToken;
public String boothId;
public String eventBrite;
public String scanedQR;
public String fname;
public String lname;
public String cname;
public String Id;
public String emailId;
public String ph;
public String note;
public String title;
public String date;
public String cat;
public String booth_fname;


public void setMyBoothFirstName(String booth_fname) {
    this.booth_fname = booth_fname;
}

public String getMyBoothFirstName() {
    return booth_fname;
}

public void setMyCategory(String cat) {
    this.cat = cat;
}

public String getMyCategory() {
    return cat;
}

public void setMyDate(String date) {
    this.date = date;
}

public String getMyDate() {

    return date;
}

public void setMyTitle(String title) {
    this.title = title;
}

public String getMyTitle() {
    return title;
}

public void setMyNote(String note) {
    this.note = note;
}

public String getMyNote() {
    return note;
}

public void setMyPh(String ph) {
    this.ph = ph;
}

public String getMyPh() {
    return ph;
}

public void setMyEmailId(String emailId) {
    this.emailId = emailId;
}

public String getMyEmailId() {
    return emailId;
}

public void setMyScanedId(String Id) {
    this.Id = Id;
}

public String getMyScanedId() {
    return Id;
}

public void setMyfname(String fname) {
    this.fname = fname;
}

public String getMyfname() {
    return fname;
}

public void setMylname(String lname) {
    this.lname = lname;
}

public String getMylname() {
    return lname;
}

public void setMycname(String cname) {
    this.cname = cname;
}

public String getMycname() {
    return cname;
}

public void setMyAccessToken(String accessToken) {
    this.accessToken = accessToken;
}

public String getMyAccessToken() {
    return accessToken;
}

public void setMyBoothId(String boothId) {
    this.boothId = boothId;
}

public String getMyBoothId() {
    return boothId;
}

public void setMyEventBrite(String eventBrite) {
    this.eventBrite = eventBrite;
}

public String getMyEvetBrite() {
    return eventBrite;
}

public void setMyScanedQR(String scanedQR) {
    this.scanedQR = scanedQR;
}

public String getMyScanedQR() {
    return scanedQR;
}

}

公共类 AutoSearchText 扩展 ListActivity {

static String rFirstName = null, rLastName = null, rCompanyName = null,
        string_qrcode;
private static final String TABLE_NAME = "qr";
private ListView listView;
static AutoCompleteTextView et;
String resp;
int a;
private MyArrayAdapter adapter;
static ProgressDialog progressDialog;
private static List<String> data, fname;
private static List<String> newdata, newdata1, qrcode, sorted_qrcode;
private static List<String> data1, sorted_visits, company;
static GlobalClass global;
Cursor cur = null;
String s = null;
String result = null;
String[] array1, array2;
String[] array, arry_qrcode;
static EditText textView;
static String clickQR = null;
TextView total;
Runnable r;
Bundle inBundle;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    inBundle = savedInstanceState;
    setContentView(R.layout.list_main);




    r = new Runnable() {

        @Override
        public void run() {

            data = new LinkedList<String>();
            fname = new LinkedList<String>();
            sorted_visits = new LinkedList<String>();
            data1 = new LinkedList<String>();
            company = new LinkedList<String>();
            newdata = new LinkedList<String>();
            newdata1 = new LinkedList<String>();
            qrcode = new LinkedList<String>();
            sorted_qrcode = new LinkedList<String>();
            global = (GlobalClass) getApplication();
            System.out.println("Start posting");
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    progressDialog = ProgressDialog.show(getParent(),
                            "Loading...", "Leads");
                }
            });

            // TODO Auto-generated method stub
            get_leads();
            total = (TextView) findViewById(R.id.textView1);
            final TextView tv = (TextView) findViewById(R.id.txt_lead);
            // Cursor cur = null;

            // data.add(s);
            System.out.println("data" + data);

            if (data != null && result != null) {
                // tv.setText(data.size()+" Leads");
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        tv.setText(data.size() + " Leads");
                    }
                });

                // tv.setText(a+" Leads");

                array = new String[data.size()];
                array1 = new String[data1.size()];
                array2 = new String[company.size()];
                arry_qrcode = new String[qrcode.size()];

                for (int i = 0; i < data.size(); i++) {
                    array[i] = data.get(i);
                    array1[i] = data1.get(i);
                    array2[i] = company.get(i);
                    arry_qrcode[i] = qrcode.get(i);
                }
                String[] a = { "1", "2" };
                adapter = new MyArrayAdapter(AutoSearchText.this, array,
                        array1, array2, arry_qrcode);
                runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        setListAdapter(adapter);
                        progressDialog.dismiss();

                    }
                });

            }

            listView = getListView();
            listView.setItemsCanFocus(false);
            listView.setTextFilterEnabled(true);
            listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

            listView.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                        int arg2, long arg3) {
                    ViewHolder holder = (ViewHolder) arg1.getTag();
                    clickQR = holder.getQrcode();
                    global.setMyScanedQR(clickQR);
                    if (isOnline()) {
                        progressDialog = ProgressDialog.show(getParent(),
                                "Verifying ..", "Please Wait..");

                        try {
                            InputMethodManager imethodManager = (InputMethodManager) getApplicationContext()
                                    .getSystemService(
                                            Context.INPUT_METHOD_SERVICE);
                            imethodManager.hideSoftInputFromWindow(
                                    textView.getWindowToken(), 0);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        new GetDataTask().execute();
                    } else {
                        alert("Warning",
                                "Please check your Data Connection");
                    }
                    // Toast.makeText(AutoSearchText.this,
                    // holder.getQrcode(),Toast.LENGTH_LONG).show();

                }
            });

        }
    };

    textView = (EditText) findViewById(R.id.et_search);

    textView.addTextChangedListener(new TextWatcher() {
        public void onTextChanged(CharSequence s, int start, int before,
                int count){
            int textlength=0;
            if(s!=null){
             textlength = s.length();
            }
            else{
                Toast.makeText(getApplicationContext(), "EDit text  is null", 600000).show();
                return;

            }

           newdata.clear();
           newdata1.clear();

           sorted_visits.clear();
           sorted_qrcode.clear();
            for (int i = 0; i < array.length; i++) {
                if (textlength <= array[i].length()) {
                    if (array[i].subSequence(0, array[i].length())
                            .toString().toUpperCase()
                            .indexOf(s.toString().toUpperCase()) != -1) {
                        newdata.add(array[i]);
                        newdata1.add(array2[i]);
                        sorted_visits.add(array1[i]);
                        sorted_qrcode.add(arry_qrcode[i]);
                    }
                }
            }
            if (newdata.size() > 0) {
                listView.setVisibility(View.VISIBLE);
                String[] a = { "1", "2" };
                adapter = new MyArrayAdapter(getParent(),
                        (String[]) newdata.toArray(new String[0]),
                        (String[]) sorted_visits.toArray(new String[0]),
                        (String[]) newdata1.toArray(new String[0]),
                        (String[]) sorted_qrcode.toArray(new String[0]));
                setListAdapter(adapter);
                listView = getListView();
            } else {

                listView.setVisibility(View.INVISIBLE);
            }

            listView.setItemsCanFocus(false);
            listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        }

        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        public void afterTextChanged(Editable s) {
            /*
             * if (newdata != null&&result!=null) { array = new
             * String[newdata.size()]; array1= new String[newdata.size()];
             * for (int i = 0; i < newdata.size(); i++) { array[i] =
             * newdata.get(i); array1[i]=newdata.get(i); } String[]
             * a={"1","2"}; adapter = new MyArrayAdapter(getParent(),
             * array,array1); setListAdapter(adapter); } listView =
             * getListView(); listView.setItemsCanFocus(false);
             * listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);}
             */}
    });

}

/*******************************************************************
 * 
 * @Desc : This method to diplsy alert when connection not available and
 *       control navigate to scan
 * @param : String
 * @return : none
 * 
 *         ********************************************************
 */

private void alert(String title, String error) {

    if (progressDialog.isShowing())
        progressDialog.dismiss();
    AlertDialog alertDialog = new AlertDialog.Builder(getParent()).create();
    alertDialog.setCancelable(false);
    alertDialog.setTitle(title);
    alertDialog.setMessage(error);
    alertDialog.setCancelable(false);
    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            try {

                global.setDisplayTab(0);
                Intent i = new Intent(getParent(), AdminTabHost.class);
                startActivity(i);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    });
    alertDialog.show();

}

private void get_leads() {
    // TODO Auto-generated method stub
    try {

        String url = "https://ap1.salesforce.com/services/apexrest/getLead?Id="
                + global.getMyBoothId();

        // URLEncoder.encode(textView.getText().toString(),"UTF-8"));
        HttpGet httpGet = new HttpGet(url);
        System.out.println("url" + url);
        // https://na7.salesforce.com/services/apexrest/GlobalNestEM/Verify_Lead?Id"+global.getMyBoothId()+"&Barcode=100000051
        HttpParams httpParameters = new BasicHttpParams();
        // set up time out connection 30s
        int timeoutConnection = 3000;
        HttpConnectionParams.setConnectionTimeout(httpParameters,
                timeoutConnection);
        int timeoutSocket = 3000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

        String token = "00DA0000000L49t!AQ8AQFxfw19eJBNw_NNxyesR.PTOiFMpZP4SrXkEpSZ3tl_Hr4btzhggN_KVwT5x3cS1o0ohcVSeIBYC1aLkhWMitSA05JUt";
        httpGet.addHeader("Authorization",
                "OAuth " + global.getMyAccessToken());
        // System.out.println("post acessToken"+global.getMyAccessToken());
        DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
        HttpResponse httpResponse;

        httpResponse = httpClient.execute(httpGet);
        result = EntityUtils.toString(httpResponse.getEntity());
        System.out.println("res for getLead" + result);
        JSONArray ja;
        String s = null;
        // progressDialog.dismiss();
        try {
            ja = new JSONArray(result);
            // JSONObject j=new JSONObject(ja);
            ja.length();
            a = ja.length();
            System.out.println("xxxx" + ja.length());
            for (int i = 0; i < ja.length(); i++) {
                String visits = null;
                String date_global = null, temp = null;
                try {
                    visits = ja
                            .getJSONObject(i)
                            .get("Attendee_NextFollowUpDate__c")
                            .toString();

                    DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
                    DateFormat df2 = new SimpleDateFormat("MM-dd-yyyy");
                    temp = df2.format(df1.parse(visits));
                    date_global = temp.replace('-', '/').toString();

                    // s=visits.replace('-','/').toString();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                rLastName = ja.getJSONObject(i)
                        .get("Attendee_LastName__c")
                        .toString();
                rCompanyName = ja.getJSONObject(i)
                        .get("Attendee_Company__c")
                        .toString();
                rFirstName = ja.getJSONObject(i)
                        .get("Attendee_FirstName__c")
                        .toString();

                System.out.println("rFirstName" + rFirstName + ja.length());
                try {
                    string_qrcode = ja.getJSONObject(i)
                            .get("Attendee_BarCode1__c")
                            .toString();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                fname.add(rFirstName);
                data.add(rFirstName + " " + rLastName);

                // data.add(rFirstName + "\n" + rLastName);
                // newdata.add(rFirstName+"\n"+rLastName);
                data1.add(date_global);
                company.add(rCompanyName);
                qrcode.add(string_qrcode);
            }
            // System.out.println(""+ja.getJSONObject(0).get("Attendee_LastName__c"));
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println("Result lead details" + result);

    } catch (ClientProtocolException e) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                alert("Warning", "Please check your Data Connection");

            }
        });
        e.printStackTrace();
    } catch (IOException e) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                alert("Warning", "Please check your Data Connection");

            }
        });
        e.printStackTrace();
    } catch (Exception e) {
        alert("Warning", "Please check your Data Connection");
    }
}

private Boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = cm.getActiveNetworkInfo();
    if (ni != null && ni.isConnected())
        return true;

    return false;
}

private void alertDialog(String string) {
    // TODO Auto-generated method stub
    AlertDialog.Builder d1 = new AlertDialog.Builder(getParent());
    d1.setMessage(string);
    d1.setTitle("Search Result");
    d1.setPositiveButton("ok", null);
    d1.setCancelable(true);
    d1.create().show();
}

public static String postPost(String s) throws NoNetWorkException {
    System.out.println("Start posting");
    global.setMyfname(null);
    global.setMyEmailId(null);
    global.setMyNote(null);
    global.setMylname(null);
    global.setMyDate(null);
    global.setMycname(null);
    global.setMyPh(null);
    global.setMyTitle(null);
    String result = null;

    try {
        String url = "https://ap1.salesforce.com/services/apexrest/Verify_Lead?Id="
                + global.getMyBoothId()
                + "&Barcode="
                + clickQR
                + "&EventBrite=" + global.getMyEvetBrite() + "";
        HttpGet httpGet = new HttpGet(url);
        System.out.println("url" + url);
        // https://na7.salesforce.com/services/apexrest/GlobalNestEM/Verify_Lead?Id"+global.getMyBoothId()+"&Barcode=100000051
        HttpParams httpParameters = new BasicHttpParams();
        // set up time out connection 30s
   /*     int timeoutConnection = 30000;
        HttpConnectionParams.setConnectionTimeout(httpParameters,
                timeoutConnection);
        int timeoutSocket = 30000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);*/
        httpGet.addHeader("Authorization",
                "OAuth " + global.getMyAccessToken());
        // System.out.println("post acessToken"+global.getMyAccessToken());
        DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
        HttpResponse httpResponse;
        httpResponse = httpClient.execute(httpGet);
        result = EntityUtils.toString(httpResponse.getEntity());
        System.out.println("Verify result" + result);
        // return result;
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        throw new NoNetWorkException();
    } catch (IOException e) {
        e.printStackTrace();
        throw new NoNetWorkException();
    }

    return result;
}

private class GetDataTask extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... params) {
        if (isOnline()) {
            try {
                Thread.sleep(0);
                resp = postPost("");
                System.out.println(" post responceforVerify= " + resp);
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (NoNetWorkException e) {
                Log.d("No NetWork", "No NetWork");
                resp = "no network";
                return resp;

            }

        }
        return resp;
    }

    @Override
    protected void onPostExecute(String result) {
        progressDialog.dismiss();
        super.onPostExecute(result);

        if (resp.equalsIgnoreCase("no network")) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    alert("Warning", "Please check your Data Connection");

                }
            });

        } else if (result != null) {
            if (!result.contains("Error__c")) {

                try {
                    // response manipulation
                    String currentDateTimeString = getdate();
                    JSONObject ja = new JSONObject(result);
                    global.setMyfname(ja.get(
                            "Attendee_FirstName__c")
                            .toString());
                    try {

                        try {
                            global.setMyCategory(ja
                                    .get("Attendee_LeadCategory__c")
                                    .toString());
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        try {
                            global.setMyEmailId(ja.get(
                                    "Attendee_EmailId__c")
                                    .toString());
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        try {
                            global.setMyNote(ja
                                    .get("Attendee_GatheredComments__c")
                                    .toString());
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        try {
                            global.setMyTitle(ja
                                    .get("Attendee_Designation__c")
                                    .toString());
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        try {
                            String v, d_g, t;
                            v = ja.get(
                                    "Attendee_NextFollowUpDate__c")
                                    .toString();

                            DateFormat df1 = new SimpleDateFormat(
                                    "yyyy-MM-dd");
                            DateFormat df2 = new SimpleDateFormat(
                                    "MM-dd-yyyy");
                            t = df2.format(df1.parse(v));
                            d_g = t.replace('-', '/').toString();
                            global.setMyDate(d_g);

                            // global.setMyDate(ja.get("Attendee_NextFollowUpDate__c").toString());
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        try {
                            global.setMyPh(ja
                                    .get("Attendee_PhoneNumber__c")
                                    .toString());
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        ja.get("Attendee_Company__c");
                        // global.setMyScanedId(ja.get("Id").toString());
                        global.setMycname(ja.get(
                                "Attendee_Company__c")
                                .toString());
                        global.setMylname(ja.get(
                                "Attendee_LastName__c")
                                .toString());
                        System.out.println("verify values" + resp);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    global.setDisplayTab(1);
                    global.setLeaddetails(true);
                    Intent edit = new Intent(getParent(), LeadDetails.class);
                    TabGroupActivity parentActivity = (TabGroupActivity) getParent();
                    parentActivity.startChildActivity("Verify", edit);

                } catch (Exception e) {
                    e.printStackTrace();
                    alertDialog("Invalid QR Code");

                }

            } else {
                try {
                    JSONObject ja = new JSONObject(result);
                    alertDialog(ja.get("Error__c").toString());
                    // startChildActivity("EditActivity", new
                    // Intent(this,LeadDetails.class));
                    /*
                     * Intent edit = new Intent(getParent(),
                     * LeadDetails.class); TabGroupActivity parentActivity =
                     * (TabGroupActivity)getParent();
                     * parentActivity.startChildActivity("LeadDetails",
                     * edit);
                     */
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        } else {
            runOnUiThread(ne
4

3 回答 3

0

我认为问题不一定出在您的代码中,当Android没有足够的内存用于前台应用程序并且它从后台应用程序的内存对象中释放时就会发生这种情况。我认为这也是您的情况。 .我认为唯一要做的就是检查您使用的对象是否为空,并使用一些默认值再次初始化它们。请参阅此处:活动生命周期以获取更多信息。

于 2012-06-25T08:25:04.767 回答
0

好的,你去,

您可以Application使用在类中设置值getApplicationContext()

((GlobalClass)getApplicationContext()).setLastName("Poptani");
于 2012-06-25T09:32:00.140 回答
0

问题肯定出在您的生命周期管理中。只要 JVM(在本例中为 Davlik)运行,静态变量的值就会存在。但是操作系统可以在它喜欢这个想法的时候杀死它——所以很可能你的变量在完全重启后是空的。

从您的源代码来看,您正在继承应用程序类。如果是这种情况,您也应该在清单中使用它。

我还在你的可运行文件中看到了问题——你在 run() 方法中执行 findViewById()——这是次优的(你应该在你的活动的 onCreateMethod() 中这样做)

您的全局存储类将无法在应用程序重新启动后继续存在 - 所有值都将丢失。

如果您喜欢状态持久性,您应该将值存储在其他地方(共享偏好是不错的选择)。为了让你的生活更轻松,你可以抓住我写的小图书馆:

这里

我将使您的生活更轻松,将对象字段编组和解组为首选项对象。

于 2012-06-25T08:28:07.453 回答