无数据库登录后如何显示用户名

时间:2017-01-16 07:24:48

标签: android

我使用过toast和textview,但我的应用程序每次都崩溃了。请看我的代码并帮助我。感谢。

我想要显示的活动:

public class Sites extends ListActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.sites);

    TextView txt = (TextView) findViewById(R.id.logged_name);
    Intent intent = getIntent();
    String name1 = intent.getStringExtra("name");
    txt.setText(name1);
}
}

我通过用户名的活动:

public class SignIn extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sign_in);
}
public void login_inside(View view) {
    EditText username = (EditText) findViewById(R.id.username_txt);
    EditText password = (EditText) findViewById(R.id.password_txt);

    if (username.getText().toString().equals("admin") && password.getText().toString().equals("admin")) {
        Intent myIntent = new Intent(SignIn.this,
                Sites.class);
        myIntent.putExtra("name",username.getText().toString());
        startActivity(myIntent);
    } else {

    }
}

3 个答案:

答案 0 :(得分:1)

扩展ListActivity会导致java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'

所以,改变这个:

public class Sites extends ListActivity {.....

有了这个:

public class Sites extends AppCompatActivity {............

答案 1 :(得分:0)

您可以使用onCreate

中的bundle读取下一个活动中的数据
 Bundle extras = getIntent().getExtras();
 TextView txt = (TextView) findViewById(R.id.logged_name);
 String value;
 if(extras != null){ // check if there is no data 
 value = extras.getString("name");
 txt.setText(value);
 } else{ "handle the null case" }

答案 2 :(得分:-2)

您可以使用共享偏好而不是通过Intent

将数据保存到sharedprefrence:

public static final String MY_PREFS_NAME = "MyPrefsFile";
 SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME,   MODE_PRIVATE).edit();
 editor.putString("name", "Samsad");
 editor.putInt("idName", 12);
 editor.commit();

从偏好中检索数据:

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
  String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
  int idName = prefs.getInt("idName", 0); //0 is the default value.
}

在文字视图中设定值

 TextView txt = (TextView) findViewById(R.id.logged_name);
 txt.setText(name );`