解决方案 »

  1.   

    package com.example.read_8_1_2_preferences;import android.os.Bundle;
    import android.app.Activity;
    import android.content.Context;
    import android.content.SharedPreferences;
    import android.content.pm.PackageManager.NameNotFoundException;
    import android.widget.TextView;public class Read_8_1_2_Preferences extends Activity
    {
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_read_8_1_2__preferences);

    Context use_my_sp_test = null;
    try
    {
    // 获取其他程序所对应的Context
    use_my_sp_test = createPackageContext(
    "com.example.december_8_1_2", 
    CONTEXT_IGNORE_SECURITY);
    }
    catch (NameNotFoundException e)
    {
    e.printStackTrace();
    }
    // 使用其他程序的Context 获取对应的 SharedPreferences
    SharedPreferences prefs = use_my_sp_test.getSharedPreferences(
    "my_sp_test", Context.MODE_WORLD_READABLE); // 读取数据
    int int1 = prefs.getInt("opentime", 0);

    TextView textView=(TextView) findViewById(R.id.textView);
    textView.setText("读取了其他程序的SharedPreferences中的数值变量"+int1);
    }
    }
    把TextView 的声明移入函数就对了
    But。。Why?
      

  2.   

    textView=(TextView) textView.findViewById(R.id.textView);引用错了
    textView这个不是你自己定义的 TextView吗? 这个TextView里面有 R.id.textView 这个控件吗?
    textView=(TextView)findViewById(R.id.textView); 
    这样才是正确的
      

  3.   

    原来的代码有问题呗:textView=(TextView) textView.findViewById(R.id.textView);你看看这会不会出问题?
    TextView textView=(TextView) findViewById(R.id.textView);你把它放回去看还报错吗
      

  4.   

    请仔细查看你之前报错的代码与修改后不报错的代码。
    之前关键代码:
    textView=(TextView) textView.findViewById(R.id.textView);-----代码1
    之后关键代码
    TextView textView=(TextView) findViewById(R.id.textView);----代码2观察到一方面你将textView的声明放在了函数内部,但这不是问题的关键,或者说仅从这个角度,都是正确的。
    关键在于你修改了findViewById(int i );这个方法的调用者。(this是继承Context、TextView是继承View,但为什么没有语法错误,)
    代码1是 textView.findViewById(R.id.textView);
    代码2是findViewById(R.id.textView);即this.findViewById(R.id.textView);
    之所以是NullPointerException,当然是因为代码1中的textView对象为null哦,应该是this,而且就算你的textView不为null,后面也会出现null,因为textView这个View本身是无法找到R.id.textView这个资源的即会返回null。仔细分析一下:
    1,因为textView你在全局进行声明且是继承View类的,所以不会语法错误。可以看看findViewById(int i );该方法到底是哪个类定义的。
    2,很巧的是,你将textView的声明放在方法内部,但同时按照之前的代码就会报错即
    TextView textView=(TextView) textView.findViewById(R.id.textView);//后面那个textView找不到,出现语法错误。
    因此你就删除后面的textView。很巧的是正确了。