Overview of common programming errors in Android development

Source: Internet
Author: User

1. Set the text color of the TextView

123 TextView tv;...tv.setTextColor(R.color.white);

In fact, the color set is the color value represented by the resource ID value of R.color.white, not the white color value under resource color: The correct practice is as follows:

1 tv.setTextColor(getResources().getColor(R.color.white));

The probability of this error is high, because both are int classes, causing the compiler to not error.

2. Read the values in the cursor

1234567 uri Uri; cursor Cursor = Contentresolver.query (URI, null null null null if (cursor! = null Code class= "JS spaces" >     string name = cursor.getstring (1); //      curosr.close ();      cursor = null

In the above statement, execution to the cursor.getstring (1) Section will report an exception, the exception is: caused by:android.database.cursorindexoutofboundsexception:index-1 requested, with a size of 4

Compilation is not a problem and will only be discovered when it is running.

The correct approach is to:

123456789 Uri uri;Cursor cursor = contentResolver.query(uri, null,null,null,null);if(cursor !=null){    if(cursor.moveToFirst()){        String name = cursor.getString(1);//    }    curosr.close();    cursor =null;}

Or:

123456789 Uri uri;Cursor cursor = contentResolver.query(uri, null,null,null,null);if(cursor !=null){    while(cursor.moveToNext()){        String name = cursor.getString(1);//    }    curosr.close();    cursor =null;}

3. Do not use functions or classes labeled deprecated, such as not using android.telephony.gsm.SmsMessage, but should use Android.telephony.SmsMessage, This avoids problems when different 3G protocols are used.

Query conditions in 4.SQLite, such as a field called name, whose field type is text, if we want to determine its name is not equal to a value (such as Zhangsan), write the following statement

1 name <> ‘zhangsan‘

However, the statement, if it encounters the name value is empty, there is a problem, that is, the name is empty above the Boolean value is False, rather than true.

The reason is probably that the judgment function in SQLite uses a similar notation:

1234 boolean judge(String self, String conditions){    if(null== self) return false;    returnself.equalsIgnoreCase(conditions);}

Where self is the value of name in the database, and conditions is the Zhangsan in the example above.

Therefore, the correct wording of the above query criteria is:

1 name <> ‘zhangsan‘or name is null

Unless you also want to filter out a record with name empty.

5. The following string resource is incorrect if you want the button to display "Delete" (yes, there is a space in the middle of the deletion), as shown below:

1 <string name="button_delete_text">删 除</string>

This comes out, eventually do not see the middle of the space, should be the Android SDK compile time, will automatically filter out the space part of the string, so should use the following way:

1 <string name="button_delete_text">删\u0020除</string>

Similarly, other special symbols can be escaped with \u00xx, such as '----\u0027, <-----\u003c, >----\u003e.

Note that the number here is 16 binary OH.

Another way is that this should be the method that XML often uses (new 2013.03.28)

& #39;

& #60;

& #62;

Don't forget the semicolon after the number, and the numbers are in decimal.

6. Context Issues:

If you call startactivity in a non-activity context, then its intent must be set:

1 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

Otherwise, an error similar to the following will be reported:

1 Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag.

And we have to beware of the implicit call startactivity in the system control:

123 TextView tv = newTextView(mContext);tv.setAutoLinkMask(Linkify.ALL);<br>tv.setText(content);

When there is a phone number/mail/url in content, and Mcontext is not a non-acitvity context, it is the context of the app (XXXActivity.this.getApplicationContext () ),

You will see the following error:

12345 android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is thisreally what you want?E/AndroidRuntime(10382):     at android.app.ContextImpl.startActivity(ContextImpl.java:622)E/AndroidRuntime(10382):     at android.content.ContextWrapper.startActivity(ContextWrapper.java:258)E/AndroidRuntime(10382):     at android.text.style.URLSpan.onClick(URLSpan.java:62)

Since the call to StartActivity in Urlspan.onclick is controlled by the system, we must pass in the activity's contex so that it does not appear as an exception, causing the program to exit.

7. Another context issue: If you have a single instance of the object, there is a registered listener behavior, then pass to this single instance

The context of the object, it must be applicationcontext, otherwise it will appear: Receiver leak error.

8. Controls can sometimes not fill the entire screen:

123456 LinearLayout panel = newLinearLayout(this);LinearLayout.LayoutParams llp = newLinearLayout.LayoutParams(        LinearLayout.LayoutParams.FILL_PARENT,        LinearLayout.LayoutParams.FILL_PARENT);panel.setLayoutParams(llp);root.addView(panel);

And it should be:

12345 LinearLayout panel = newLinearLayout(this);LinearLayout.LayoutParams llp = newLinearLayout.LayoutParams(        LinearLayout.LayoutParams.FILL_PARENT,        LinearLayout.LayoutParams.FILL_PARENT);root.addView(panel. llp);

9. Start the service in the following manner, but the service is not up

12 Intent service = newIntent(this, FuncService.class);startService(service);

Most likely forgot to register in Androidmanifest.xml Funcservice

1 <service android:name="com.android.example.FuncService"/>

Why in the 10.TextView there are some lines at the end of the "..." character, of course not all phones are problematic, originally I thought it might be

The ROM problem of the phone, seriously review the code, found the following code:

12 mIntroView = (TextView) findViewById(R.id.description);mIntroView.setEllipsize(TruncateAt.END);

The problem is the 2nd line above, which was preceded by the number of lines to qualify the text, and then the limit was removed, without removing the above code.

The line code will cause a lot of Rom: as long as the text of a line in a cell phone screen can not display, it automatically

End-of-line truncation and add "..." at the end of the row, and there was no problem because: when all is displayed, I call the following method:

1 mIntro.setMaxLines(Integer.MAX_VALUE);

11. Do not believe that tools, such as eclipse inside the breakpoint encountered multi-threaded what, often do not work/go, and if the statement is empty and will not go, this time not too early to jump to the point where the breakpoint error,

So each project should have a log switch, by looking at the log to confirm that a path is going to or a variable value, ...

The month in 12.Java starts with 0, so when you format the month, remember to add 1 to the original value, such as

12345678910111213141516171819 Calendar calendar = Calendar.getInstance();            if(!TextUtils.isEmpty(dateTimes)){                long milliseconds = WLDateUtils.parseDayTime(dateTimes);                calendar.setTimeInMillis(milliseconds);            }            final int old_year = calendar.get(Calendar.YEAR);            final int old_month = calendar.get(Calendar.MONTH);            final int old_day = calendar.get(Calendar.DAY_OF_MONTH);            mDatePickerDialog = new DatePickerDialog(this, new OnDateSetListener(){                @Override                public void onDateSet(DatePicker view, int year,                        int monthOfYear, int dayOfMonth) {                    if(year != old_year || monthOfYear != old_month || dayOfMonth != old_day){                        String dateTimes = String.format("%04d-%02d-%02d", year,                                monthOfYear + 1, dayOfMonth);//月份是从0开始的                    }                }            },            old_year, old_month, old_day);

13. Set the ListView's split line, if not the picture, you should pay attention to the order:

1234567 mListView = new ListView(this);        mListView.setCacheColorHint(0);        mListView.setBackgroundDrawable(null);        mListView.setDivider(getResources().getDrawable(R.drawable.list_divider));        mListView.setDividerHeight(2);其中:<drawable name="list_divider">#00CCCC00</drawable>

That is, the Setdividerheight function should be after setdivider, otherwise this split line is invalid

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.