您好我正在尝试编写一个包含多个内容的Android应用。 我有很多麻烦试图摆脱这种nullpoinerexception。 当我点击应用程序中的按钮时,它会崩溃。 有人可以帮忙吗?
MainActivity.java:
package com.smoke.rms;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
Button button1, button2;
LinearLayout ourlayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Button1 = visit_our_site
button1 = (Button) findViewById(R.id.button1);
// Button2 = youtube_button
button2 = (Button) findViewById(R.id.button2);
// set onclick listeners for buttons
button1.setOnClickListener(this);
button2.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Context context = null;
switch (v.getId()) {
case R.id.button1:
Intent intent1 = new Intent(context, WebActivity.class);
startActivity(intent1);
break;
case R.id.button2:
Intent intent2 = new Intent(context, YouTubeActivity.class);
startActivity(intent2);
break;
}
}
// Initiating Menu XML file (menu.xml)
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.layout.menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.webView:
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"treavor.brown5875@gmail.com"});
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
return false;
}
}
main.xml中:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/visit_our_site" />
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/youtube" />
</LinearLayout>
答案 0 :(得分:3)
唔。按钮单击中显示Context context = null
....显然这是问题
答案 1 :(得分:2)
我认为你的错误来自第39行
Context context = null;
你应该删除这一行和
使用
实现您的意图 Intent intent1 = new Intent(MainActivity.this, WebActivity.class);
startActivity(intent1);
你应该对意图2
一样