2017-02-23 43 views
-1

这里是我的代码,我设置计数值为-1。我只给下一个按钮计数了<。并为prev按钮计数> = 0。另外声明(Toast消息)不起作用。请帮我解决这个错误。我得到索引超出限制的异常和吐司消息的错误未来

public class story extends AppCompatActivity { 
Button next; 
Button prev; 
TextView t; 
int count=-1; 
int[] stories = { 
     R.string.firststory, 
     R.string.story2, 
     R.string.story3, 
     R.string.story4, 
     R.string.story5, 
     R.string.story6, 
     R.string.story7, 
     R.string.story8, 
     R.string.story9, 
     R.string.story10, 
}; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.story); 

    next = (Button) this.findViewById(R.id.next); 
    prev = (Button) this.findViewById(R.id.prev); 
    t = (TextView) this.findViewById(R.id.textView2); 
    t.setText(Html.fromHtml(getString(stories[0]))); 
    next.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      // Perform action on click 
      count=count+1; 
      try{ 
      if(count<10) { 
       t.setText(Html.fromHtml(getString(stories[count]))); 
      } 
       else{ 
       Toast toast=Toast.makeText(getApplicationContext(),"This is Last story",Toast.LENGTH_SHORT); 
      } 
      } 
      catch(Exception e) 
      { 

      } 
     } 
    }); 
    prev.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      // Perform action on click 
      count=count-1; 
      try{ 
      if(count>=0) 
      { 
      t.setText(Html.fromHtml(getString(stories[count]))); 
      } 
      else{ 
       Toast toast=Toast.makeText(getApplicationContext(),"This is first story",Toast.LENGTH_SHORT); 
      } 
      } 
      catch(Exception e){ 

      } 
     } 
    }); 
} 
} 
+1

请提供logcat错误 – Malik

+1

吐司没有显示,因为你从来没有打过电话toast.show() – Malik

回答

0

认为,如果用户按下按钮next太多次会发生什么 - count将高于10(比如说12)。现在用户按下prev按钮。 count将是11,条件是TRUE - 它大于0,因此您将尝试访问阵列上的第11个项目。
你不能增加计数器的值太多:

next.setOnClickListener(new View.OnClickListener() { 
    public void onClick(View v) { 
     // Perform action on click 
     try{ 
     if(count<10) { 
      count=count+1; 
      t.setText(Html.fromHtml(getString(stories[count]))); 
     } else {... 

移动的count = count + 1的条件内。这样它不会超过它的限制。
对第二个按钮做同样的操作。
而对于Toast - 您永远不会调用.show()方法。

+0

但是即使它正数超过或负数超过了,我写了条件,所以,它不会进入右边? – Chitrapandi

+0

你试过我的解决方案吗?你的情况只有一半是正确的 - 如果你多次按下“下一步”按钮并且“计数= 12”,那么情况良好并且将显示吐司,但是当你按下“上一页”时,计数将会是递减到11,条件'count> = 0'是真的,你的程序将尝试访问数组中的第11个项目并且会崩溃。照我写的那样做 - 在** if语句之后增加和减少计数器**。 – TDG

0

首先,敬酒:

要显示你需要调用 “秀()” 方法敬酒消息。尝试添加以下行创建你的面包后:

toast.show(); 

二,指标:

你可能acessing你的阵列比0。您应该使用调试器大于9或较小的值(或者如果您不熟悉调试器,请插入日志消息)在访问数组之前检查“count”变量的值。

0

您正在省略try块中发生的异常。请使用e.printStackTrace()打印它,以便您可以知道确切的错误以及发生的行。

和吐司,正如其他人所提到的,使用show()来显示它。

Toast toast = Toast.makeText(getApplicationContext(),"This is first story",Toast.LENGTH_SHORT); 
toast.show(); 

或直接,

Toast.makeText(getApplicationContext(),"This is first story",Toast.LENGTH_SHORT).show();