Я знаю, как работают общие настройки, но я просто не знаю, куда вставить код в код ниже, чтобы сохранить данные пользователей. У меня есть логин, фоновая задача, которая выполняет всю работу и регистрацию. Я хочу, чтобы приложение открывалось для страницы выплеска когда пользователь вошел в in.Cant это цифра из других ответовОбщие предпочтения, куда они идут?
Login.java
Button bttnLogin;
EditText loginEmail, loginPassword;
TextView regLink;
AlertDialog.Builder alert;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginEmail = (EditText) findViewById(R.id.email);
loginPassword = (EditText) findViewById(R.id.password);
regLink = (TextView) findViewById(R.id.regLink);
regLink.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
startActivity(new Intent(Login.this, Register.class));
}
});
bttnLogin = (Button) findViewById(R.id.bttnLogin);
bttnLogin.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
if (loginEmail.getText().toString().equals("") || loginPassword.getText().toString().equals(""))
{
alert = new AlertDialog.Builder(Login.this);
alert.setTitle("Login Failed");
alert.setMessage("Try again");
alert.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
});
AlertDialog alertDialog = alert.create();
alertDialog.show();
} else //if user provides proper data
{
BackgroundTask backgroundTask = new BackgroundTask(Login.this);
backgroundTask.execute("login", loginEmail.getText().toString(), loginPassword.getText().toString());
}
}
});
Register.java
private Button regButton;
public EditText regName;
public EditText regEmail;
public EditText regPassword;
public EditText conPassword;
private AlertDialog.Builder alert;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
regName = (EditText) findViewById(R.id.name);
regEmail = (EditText) findViewById(R.id.email);
regPassword = (EditText) findViewById(R.id.password);
conPassword = (EditText) findViewById(R.id.conPassword);
regButton = (Button) findViewById(R.id.regButton);
regButton.setOnClickListener(this);
}
@Override
public void onClick(View v)
{
if (regName.getText().toString().equals("") || regEmail.getText().toString().equals("") || regPassword.getText().toString().equals("") || conPassword.getText().toString().equals(""))
{
alert = new AlertDialog.Builder(Register.this);
alert.setTitle("Something not quite right");
alert.setMessage("Please fill in all the fields");
alert.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
}
});
AlertDialog alertDialog = alert.create();
alertDialog.show();
} else if (!(regPassword.getText().toString().equals(conPassword.getText().toString())))
{
alert = new AlertDialog.Builder(Register.this);
alert.setTitle("Passwords do not match");
alert.setMessage("Try Again");
alert.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
conPassword.setText("");
regPassword.setText("");
}
});
AlertDialog alertDialog = alert.create();
alertDialog.show();
}
else //if user provides proper data
{
BackgroundTask backgroundTask = new BackgroundTask(Register.this);
backgroundTask.execute("register", regName.getText().toString(), regEmail.getText().toString()
, regPassword.getText().toString(), conPassword.getText().toString());
}
BackgroundTask.java
public class BackgroundTask extends AsyncTask<String,Void,String>
{
private Context context;
private Activity activity;
private String reg_url = "http://blaah.com/register.php";
private String login_url = "http://blaah.com/login.php";
private AlertDialog.Builder builder;
private ProgressDialog progressDialog;
public BackgroundTask(Context context)
{
this.context = context;
activity = (Activity) context;
}
@Override
protected void onPreExecute()
{
builder = new AlertDialog.Builder(activity);
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Please wait");
progressDialog.setMessage("Connecting to Server...");
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
}
@Override
protected String doInBackground(String... params)
{
String method = params[0];
if (method.equals("register"))
{
try
{
URL url = new URL(reg_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String name = params[1];
String email = params[2];
String username = params[3];
String password = params[4];
String data = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(email, "UTF-8") + "&" +
URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line = "";
while ((line = bufferedReader.readLine()) != null)
{
stringBuilder.append(line).append("\n");
}
httpURLConnection.disconnect();
Thread.sleep(8000);
return stringBuilder.toString().trim();
} catch (MalformedURLException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
else if (method.equals("login"))
{
try
{
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String username,password;
username = params[1];
password = params [2];
String data = URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8") + "&" +
URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line = "";
while ((line = bufferedReader.readLine()) != null)
{
stringBuilder.append(line + "\n");
}
httpURLConnection.disconnect();
Thread.sleep(5000);
return stringBuilder.toString().trim();
} catch (MalformedURLException e)
{
e.printStackTrace();
} catch (ProtocolException e)
{
e.printStackTrace();
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
return null;
}
@Override
protected void onProgressUpdate(Void... values)
{
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String json)
{
try
{
progressDialog.dismiss();
Log.v("JSON", json);
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
JSONObject jsonobject = jsonArray.getJSONObject(0);
String code = jsonobject.getString("code");
String message = jsonobject.getString("message");
if(code.equals("reg_true"))
{
showDialog("Sucessful registration.Thank you.Enjoy_AS!", message, code);
}
else if (code.equals("reg_false"))
{
showDialog("User Already exists", message, code);
}
else if (code.equals("login_true"))
{
Toast.makeText(context, "You are logged in", Toast.LENGTH_LONG).show();
Intent intent = new Intent(activity, SplashScreen.class);
activity.startActivity(intent);
} else if (code.equals("login_false"))
{
showDialog("Login Error", message, code);
}
} catch (JSONException e){
e.printStackTrace();
}
}
public void showDialog(String title,String message,String code)
{
builder.setTitle(title);
if (code.equals("reg_true") || code.equals("reg_false"))
{
builder.setMessage(message);//message form server
builder.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
dialog.dismiss();
activity.finish();
}
});
}
else if (code.equals("login_false"))
{
builder.setMessage(message);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
EditText loginEmail, loginPassword;
loginEmail = (EditText) activity.findViewById(R.id.email);
loginPassword = (EditText) activity.findViewById(R.id.password);
loginEmail.setText("");
loginPassword.setText("");
dialog.dismiss();
}
});
}
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
заставка Я хочу, чтобы приложение, чтобы открыть для
final String TAG = this.getClass().getName();
private static int SPLASH_TIME_OUT = 4000;
private TextView saying;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//this.requestWindowFeature(Window.FEATURE_NO_TITLE);
supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash_screen);
saying = (TextView) findViewById(R.id.saying);
Typeface mainHead = Typeface.createFromAsset(getAssets(), "fonts/emporo.TTF");
saying.setTypeface(mainHead);
//Set text custom font for subhead text
new Handler().postDelayed(new Runnable()
{
@Override
public void run()
{
// This method will be executed once the timer is over
// Start your app main activity
Intent i = new Intent(SplashScreen.this, HomeScreen.class);
startActivity(i);
// close this activity
finish();
}
}, SPLASH_TIME_OUT);
}
}
попытался это, но не работало, не дает мне ошибку на булевой isLogin = session.isLoggedIn() ;. Без сомнения, я делаю что-то неправильно. – user1958789
Какая ошибка вы получаете? –
Эй, извините, был занят, ошибка при запуске приложения, java.lang.NullPointerException: попытка вызвать виртуальный метод 'boolean com.example.xxxxxxxx.project.userdata.SessionManagement.isLoggedIn()' в ссылке нулевого объекта. Я имею создать переменную для сеанса в session.isLoggedIn(); . Я поместил логический isLogin в метод onCreate для splashscreen. Но он просто выдает ошибку. – user1958789