我在Mainactivity
上使用以下代码将用户名存储为AlertDialog
中的字符串。
但是,我想使用SharedPreferences
或任何方法(如果有的话)存储用户名,当用户打开应用程序时,最初存储的用户名将首先显示。
private void request_user_name() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Enter name:");
final EditText input_field = new EditText(this);
String e = input_field.getText().toString();
builder.setView(input_field);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
name = input_field.getText().toString();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
request_user_name();
}
});
builder.show();
}
我使用了像下面这样的共享Prefrences,但它不起作用
private void request_user_name() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Enter name:");
final EditText input_field = new EditText(this);
String e = input_field.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(username, e);
editor.commit();
builder.setView(input_field);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
name = input_field.getText().toString();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
request_user_name();
}
});
builder.show();
}
以下是首次初始化应用时的图片
我的整个Mainactivity文件是
package com.nepalpolice.mnemonics.chat;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.nepalpolice.mnemonics.R;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
private Button add_room;
private EditText room_name;
EditText edittext;
private Toolbar mainToolbar;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String username = "userKey";
ProgressBar progressBar;
private ListView listView;
private ArrayAdapter<String> arrayAdapter;
private ArrayList<String> list_of_rooms = new ArrayList<>();
private String name;
private DatabaseReference root = FirebaseDatabase.getInstance().getReference().getRoot();
SharedPreferences sharedpreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
mainToolbar = (Toolbar) findViewById(R.id.main_chatbar);
setSupportActionBar(mainToolbar);
getSupportActionBar().setTitle("Chat Rooms");
progressBar= (ProgressBar) findViewById(R.id.webViewProgressfaq);
listView = (ListView) findViewById(R.id.listView);
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list_of_rooms);
listView.setAdapter(arrayAdapter);
if(isNetworkStatusAvialable (getApplicationContext())) {
request_user_name();
root.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Set<String> set = new HashSet<String>();
Iterator i = dataSnapshot.getChildren().iterator();
while (i.hasNext()) {
set.add(((DataSnapshot) i.next()).getKey());
}
list_of_rooms.clear();
list_of_rooms.addAll(set);
arrayAdapter.notifyDataSetChanged();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}else{
Toast.makeText(getBaseContext(), "You're Offline!", Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.VISIBLE);
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(),Chat_Room.class);
intent.putExtra("room_name",((TextView)view).getText().toString() );
intent.putExtra("user_name",name);
startActivity(intent);
}
});
}
private void request_user_name() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Enter name:");
final EditText input_field = new EditText(this);
builder.setCancelable(false);
builder.setView(input_field);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
name = input_field.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("username", name);
editor.commit();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
request_user_name();
}
});
builder.show();
}
public static boolean isNetworkStatusAvialable (Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
}
}
答案 0 :(得分:1)
更改
editor.putString(username, e);
editor.commit();
builder.setView(input_field);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
name = input_field.getText().toString();
}
});
要:
builder.setView(input_field);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
name = input_field.getText().toString();
editor.putString("username", name);
editor.commit();
}
});
您尝试在用户输入任何内容之前保存用户名并按“确定”
修改强>
要在开头设置值:
创建EditText
时设置用户名的值,否则如果username
不存在,则会设置为空白字符串
final EditText input_field = new EditText(this);
input_field.setText(sharedpreferences.getString("username",""));
强制光标位于EditText
add:
input_field.setSelection(input_field.getText().length());
答案 1 :(得分:0)
如果您已保存数据,则不会在“确定”按钮单击上保存用户名并显示已保存的用户名设置文本。
用下面的替换你的功能,你会看到你的预期结果。
private void request_user_name() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Enter name:");
final EditText input_field = new EditText(this);
//String e = input_field.getText().toString();
final SharedPreferences.Editor editor = sharedpreferences.edit();
builder.setView(input_field);
String savedName = sharedpreferences.getString(username,"");
input_field.setText(savedName);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String name = input_field.getText().toString();
editor.putString(username, name);
editor.apply();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
request_user_name();
}
});
builder.show();
}