我正在开发一个应用程序,它需要从我们有的响应中更改TextView。 但是当我试图在我想要的方法中使用TextView.setText
方法时,应用程序崩溃了。 但它仍然在同一类的其他方法上工作。 如果在使用TextView.SetText
方法之前调用AsyncTask方法,是否有可能从AsyncTask方法中发生错误?
下面是我的Java课:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private static final int INTERNET_REQUEST_CODE = 123;
private static final int STORAGE_REQUEST_CODE = 213;
private static final int DEFAULT_REQUEST_CODE = 232;
private Toolbar toolbar;
private Button btPasteUrl;
private Button btDownload;
private EditText urlEditText;
private ProgressBar progressBar;
private TextView username;
private TextView caption;
private CircleImageView profilePic;
private ImageView mediaPreview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initializing views by calling init() method
init();
//username.setText working here
username.setText("hr.getUsername()");
//Set the ActionBar
setSupportActionBar(toolbar);
//set the onClickListener() for btPasteUrl button
btPasteUrl.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pasteUrl();
}
});
//set the onClickListener() for btDownload
btDownload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
initCall();
}
});
}
/* method to initialize views */
private void init() {
toolbar = findViewById(R.id.toolbar);
btPasteUrl = findViewById(R.id.buttonPasteUrl);
btDownload = findViewById(R.id.buttonDownload);
urlEditText = findViewById(R.id.urlEditText);
progressBar = findViewById(R.id.mediaLoadingBar);
username = findViewById(R.id.username);
caption = findViewById(R.id.caption);
profilePic = findViewById(R.id.profilePic);
mediaPreview = findViewById(R.id.mediaPreview);
}
/* method to validate url */
private boolean checkUrl(String url) {
//REGULAR EXPRESSION for validation of url
String REGEX = "https://www.instagram.com/p/(.*?)/(.*?)";
//pattern to check the url with REGULAR EXPRESSION
Pattern postsUrlPattern = Pattern.compile(REGEX);
//check the url with the help of matcher with pattern
Matcher matcher = postsUrlPattern.matcher(url);
//return if the pattern matches or not
return matcher.matches();
}
/* method to paste the url from clipboard */
private void pasteUrl() {
//get the clipboard manager
final ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
//paste the url when the btPasteUrl button is clicked
if (clipboard != null) {
try {
//trim any extra white spaces
String url = (Objects.requireNonNull(clipboard.getPrimaryClip()).getItemAt(0).getText()).toString().trim();
//set the url in EditText Box
urlEditText.setText(url);
} catch (NullPointerException e) {
e.getLocalizedMessage();
}
}
}
/* method to initiate call from CreateCallTask class */
private void initCall() {
if (urlEditText != null) {
if (checkUrl(urlEditText.getText().toString())) {
//REGULAR EXPRESSION for validation of url
String REGEX = "https://www.instagram.com/p/(.*?)/(.*?)";
//pattern to check the url with REGULAR EXPRESSION
Pattern postsUrlPattern = Pattern.compile(REGEX);
//check the url with the help of matcher with pattern
Matcher matcher = postsUrlPattern.matcher(urlEditText.getText().toString());
String url = "";
if (matcher.matches()) {
url = "https://www.instagram.com/p/" + matcher.group(1) + "/";
} else {
Log.e(TAG, "downloadMedia: pattern does not matches");
Toast.makeText(this, "Invalid URL", Toast.LENGTH_SHORT).show();
}
Log.e(TAG, "downloadMedia: " + url);
new CreateCallTask(this).execute(url);
}
}
}
/* method to receive response from CreateCallTask class */
public void receiveResponse(PostsResponse response) {
/*TO DO: When the response is received from CreateCallTask Method */
//Check if the response is not empty
if (response != null) {
Log.e(TAG, "receiveResponse: reposnse" + response);
//get the object of HandleResponse class
HandleResponse hr = new HandleResponse(response);
//Crashes the app if username.setText is used
username.setText(hr.getUsername());
//Working here
Log.e(TAG, "receiveResponse: username " + hr.getUsername() );
}
}}
下面是XML代码:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorBackground"
tools:context=".acitivities.MainActivity">
<include
android:id="@+id/toolbar_layout"
layout="@layout/toolbar_layout" />
<androidx.cardview.widget.CardView
android:id="@+id/urlCardViewContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/toolbar_layout"
android:layout_margin="@dimen/dimen_8dp"
app:cardCornerRadius="12dp"
app:cardElevation="@dimen/dimen_4dp">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/dimen_8dp">
<TextView
android:id="@+id/headerTextView"
style="@style/TextAppearance.MaterialComponents.Headline4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginBottom="@dimen/dimen_8dp"
android:text="@string/header_enter_url"
android:textColor="@color/colorPrimary" />
<EditText
android:id="@+id/urlEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/headerTextView"
android:layout_marginTop="@dimen/dimen_8dp"
android:background="@drawable/edittext_bg"
android:hint="@string/edittext_hint"
android:inputType="text"
android:maxLines="1" />
<Button
android:id="@+id/buttonDownload"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/urlEditText"
android:layout_alignParentEnd="true"
android:layout_marginTop="@dimen/dimen_8dp"
android:text="@string/button_download" />
<Button
android:id="@+id/buttonPasteUrl"
style="@style/Widget.MaterialComponents.Button.OutlinedButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/urlEditText"
android:layout_marginTop="@dimen/dimen_8dp"
android:layout_marginEnd="@dimen/dimen_8dp"
android:layout_toStartOf="@id/buttonDownload"
android:text="@string/button_paste_url" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/urlCardViewContainer"
android:layout_marginBottom="40dp"
android:clipChildren="false"
android:clipToPadding="false">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/dimen_8dp"
android:layout_marginEnd="@dimen/dimen_8dp"
android:layout_marginBottom="@dimen/dimen_24dp">
<androidx.cardview.widget.CardView
android:id="@+id/downloadingCardViewContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/dimen_8dp">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RelativeLayout
android:id="@+id/mediaPreviewContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/mediaPreview"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="@dimen/dimen_8dp"
android:src="@drawable/img_bg" />
<ProgressBar
android:id="@+id/mediaLoadingBar"
android:layout_centerInParent="true"
style="@style/Widget.AppCompat.ProgressBar.Horizontal"
android:progress="100"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
<LinearLayout
android:id="@+id/usernameContainerLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/dimen_8dp"
android:layout_marginEnd="@dimen/dimen_8dp"
android:layout_marginBottom="@dimen/dimen_8dp"
android:layout_toEndOf="@id/mediaPreviewContainer"
android:orientation="horizontal">
<de.hdodenhof.circleimageview.CircleImageView
android:id="@+id/profilePic"
android:layout_width="40dp"
android:layout_height="40dp"
android:src="@drawable/img_bg" />
<TextView
android:id="@+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/dimen_8dp"
android:layout_marginTop="@dimen/dimen_8dp"
android:gravity="center_vertical"
android:text="username" />
</LinearLayout>
<TextView
android:id="@+id/caption"
android:layout_width="210dp"
android:layout_height="wrap_content"
android:layout_below="@id/usernameContainerLayout"
android:layout_marginStart="@dimen/dimen_8dp"
android:layout_marginBottom="@dimen/dimen_8dp"
android:layout_toEndOf="@id/mediaPreviewContainer"
android:ellipsize="end"
android:maxLines="3"
android:text="dafjkjadhkjadhskjhafdkjhfkjahdfkjhasfkjakjdfkjfanjvncjvnzmcvzmzn,cv" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
</ScrollView>
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:id="@+id/bottomSheetContainerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/urlCardViewContainer"
android:layout_alignParentBottom="true"
android:clipChildren="false"
android:clipToPadding="false">
<include layout="@layout/download_layout" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</RelativeLayout>
错误:错误屏幕截图
在CreateCallTask
中,您正在调用此方法ReceiveResponse
,该方法尚未初始化您的用户名,这就是您使用nullpointer的原因
当您在CreateCallTask
中调用该方法时,该类不知道username是否已初始化,因为它只是从您的类中调用一个方法,而不会膨胀视图