I'm trying to get e-mail addresses from parse User class,
here I'm trying to get other users email id's when logging in a
user, logged in users email id is showing but other users email ids
are not showing always null
I try use master key also, still not working ,
below is my java code.
String objectId;
protected TextView txtv;
protected TextView txtv1;
protected ImageView txtv2;
protected ImageView txtv3;
protected TextView individualOrganization;
Button emailPerson;
Button callPerson;
Button callPersonTelephone;
ParseObject personObject;
String personEmail;
String personNumber;
String personNumberTelephone;
ParseQuery query;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_individual);
txtv =(TextView)findViewById(R.id.txt123);
txtv1 =(TextView)findViewById(R.id.coporateSector);
txtv2 =(ImageView)findViewById(R.id.txt12345);
txtv3 =(ImageView)findViewById(R.id.txt123456);
individualOrganization =(TextView) findViewById(R.id.individualOrganization);
Intent i =getIntent();
objectId = i.getStringExtra("objectId");
ParseQuery<ParseUser> query = ParseUser.getQuery();
//query.put("useMasterKey", true);
query.setLimit(2000);
query.include("email");
query.getInBackground(objectId, new GetCallback<ParseUser>() {
#Override
public void done(final ParseUser object, com.parse.ParseException e) {
if (e == null) {
personObject = object;
String username = object.getString("firstname");
txtv.setText(username + " " + object.getString("lastname"));
String position = object.getString("position");
txtv1.setText(position);
String organizationName = object.getString("organizationName");
individualOrganization.setText(organizationName);
URL url = null;
try {
url = new URL("" + object.getString("image"));
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
Glide.with(getApplicationContext())
.load(String.valueOf(url))
.into(txtv2);
try {
url = new URL("" + object.getString("image"));
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
Glide.with(getApplicationContext())
.load(String.valueOf(url))
.into(txtv3);
// try{
// JSONObject jsonObject = parseObjectToJson(object);
// Log.d("Object", jsonObject.toString());
// Log.d("Email", "+" + object.get("email"));
// personNumber = jsonObject.getString("telephone");
// //personEmail = jsonObject.getString("email");
// personEmail= object.getEmail();
//
// }catch (JSONException je){
// }catch (ParseException pe){
// } catch (com.parse.ParseException e1) {
// e1.printStackTrace();
// }
} else {
}
callPerson = (Button) findViewById(R.id.individualMobile) ;
personNumber = object.getString("mobile");
callPerson.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+personNumber));
startActivity(i);
}
});
if(personNumber==null || personNumber.equals("") || personNumber.equals(" ")){
callPerson.setClickable(false);
callPerson.setEnabled(false);
callPerson.setVisibility(View.GONE);
}
else{
callPerson.setEnabled(true);
callPerson.setClickable(true);
callPerson.setVisibility(View.VISIBLE);
}
callPersonTelephone = (Button) findViewById(R.id.individualTelephone);
personNumberTelephone = object.getString("telephone");
callPersonTelephone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(Intent.ACTION_DIAL,Uri.parse("tel:"+personNumberTelephone));
startActivity(i);
}
});
if(personNumberTelephone==null || personNumberTelephone.equals("") || personNumberTelephone.equals(" ") || personNumberTelephone.equals("6855")){
callPersonTelephone.setClickable(false);
callPersonTelephone.setEnabled(false);
callPersonTelephone.setVisibility(View.GONE);
}
else{
callPersonTelephone.setEnabled(true);
callPersonTelephone.setClickable(true);
callPersonTelephone.setVisibility(View.VISIBLE);
}
emailPerson = (Button)findViewById(R.id.individualEmail);
object.put("useMasterKey", true);
personEmail= object.getString("email");
emailPerson.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_SEND);
i.setData(Uri.parse("mailto:"));
i.setType("plain/text");
i.putExtra(Intent.EXTRA_EMAIL, new String[] {personEmail});
startActivity(i);
}
});
if(personEmail==null || personEmail.equals("") || personEmail.equals(" ")){
emailPerson.setClickable(false);
emailPerson.setEnabled(false);
emailPerson.setVisibility(View.GONE);
}
else{
emailPerson.setEnabled(true);
emailPerson.setClickable(true);
emailPerson.setVisibility(View.VISIBLE);
}
individualOrganization.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String organizationID = personObject.getString("organizationID");
if(organizationID == null || organizationID.equals("")){
Toast.makeText(SingleIndividual.this, "Sorry No Organization Available!", Toast.LENGTH_SHORT).show();
}else{
Intent i = new Intent(getApplicationContext(), SingleCorporate.class);
i.putExtra("objectId", organizationID);
i.putExtra("image", organizationID);
startActivity(i);
}
}
});
}
});
}
private JSONObject parseObjectToJson(ParseObject parseObject) throws ParseException, JSONException, com.parse.ParseException {
JSONObject jsonObject = new JSONObject();
parseObject.fetchIfNeeded();
Set<String> keys = parseObject.keySet();
for (String key : keys) {
Object objectValue = parseObject.get(key);
if (objectValue instanceof ParseObject) {
jsonObject.put(key, parseObjectToJson(parseObject.getParseObject(key)));
} else if (objectValue instanceof ParseRelation) {
} else {
jsonObject.put(key, objectValue.toString());
}
}
return jsonObject;
}
}
Master Key can only be used from your server code, not client code. Making your users public read is an option, albeit a very poor one. It would be a better idea to have a cloud code function in which you validate a user session, ensure they're able to access this information, and do the query from there, using the master key.
Related
when i am doing offline login my app is crashing...and showing the error
Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference
In Online it is working fine no issues but in offline it is crashing not at all giving where the issue is please help me in this
public class MainActivity extends AppCompatActivity {
**// Initializing variables**
EditText login;
EditText password;
String statusRes;
String id;
String projectName;
String loginValue;
String stockPoint;
JSONObject myRespObject = null;
public static final String Passkey = "passKey";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("LOGIN");
setContentView(R.layout.login);
login = (EditText) findViewById(R.id.loginname);
password = (EditText) findViewById(R.id.Password);
final Button saveme = (Button) findViewById(R.id.save);
**SharedPreferences sharedpreferences = getSharedPreferences(AppConstants.MyPREFERENCES, Context.MODE_PRIVATE);
saveme.setOnClickListener(new Button.OnClickListener() {
public URL url;
public void onClick(android.view.View v) {
if (!CheckNetwork.isInternetAvailable(MainActivity.this){
if (!validate()) {
onLoginFailed();
return;
}
SharedPreferences prefs = getSharedPreferences(AppConstants.MyPREFERENCES, Context.MODE_PRIVATE);
String loginValue = prefs.getString(AppConstants.LOGIN_VALUE, "");
String Passkey = prefs.getString(AppConstants.PASS_KEY, "");
String Internet = prefs.getString("Internet", "false");
String projectName = prefs.getString(AppConstants.PROJECT_NAME, "");
String stockPoint = prefs.getString(String.valueOf(AppConstants.STOCK_POINT),"");
String id = prefs.getString(AppConstants.ID, "");
Intent profactivity = new Intent(MainActivity.this, View.class);
profactivity.putExtra("Internet", false);
profactivity.putExtra("loginValue", loginValue);
profactivity.putExtra("id", id);
profactivity.putExtra("projectName", projectName);
profactivity.putExtra("stockPoint", stockPoint);
startActivity(profactivity);
**Toast.makeText(MainActivity.this, "Offline Login ", Toast.LENGTH_SHORT).show();
finish();
}
****for the above code, here it is throughing the error**
try {
final String loginValue = URLEncoder.encode(login.getText().toString(), "UTF-8");
final String passValue = URLEncoder.encode(password.getText().toString(), "UTF-8");
try {
new Thread(new Runnable() {
**//Thread to stop network calls on the UI thread**
public void run() {
//Request the HTML
ArrayList<String> list = null;
try {
String loginValue = URLEncoder.encode(login.getText().toString(), "UTF-8");
String passValue = URLEncoder.encode(password.getText().toString(), "UTF-8");
String ROOT_URL = getResources().getString(R.string.ROOT_URL) + "/api/v1/user/signIn?loginName=" + loginValue + "&password=" + passValue;
Log.i("httpget", "################" + ROOT_URL);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(ROOT_URL);
HttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() == 200) {
String server_response = EntityUtils.toString(response.getEntity());
myRespObject = new JSONObject(server_response);
//Do something with the response
//Toast.makeText(getBaseContext(),server_response,Toast.LENGTH_LONG).show();
statusRes = myRespObject.getString("status");
JSONObject respObject = myRespObject.getJSONObject("response");
id = respObject.getString("_id");
AppConstants._ID = id;
projectName = respObject.getString("projectName");
Actors actor = new Actors();
list = new ArrayList<>();
JSONArray jsonArray = respObject.getJSONArray("stockPoint");
Intent i = getIntent();
Serializable subject = i.getSerializableExtra("stockPoint");
if (jsonArray != null) {
int len = jsonArray.length();
for (int k = 0; k < len; k++)
list.add(jsonArray.get(k).toString());
}
actor.setStockPoint(list);
AppConstants.STOCK_POINT = stockPoint;
stockPoint = respObject.getString("stockPoint");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
final ArrayList<String> finalList = list;
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
statusRes = myRespObject.getString("status");
} catch (JSONException e) {
e.printStackTrace();
}
if (statusRes.equalsIgnoreCase("success")) {
SharedPreferences sharedpreferences = getSharedPreferences(AppConstants.MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(AppConstants.LOGIN_VALUE, loginValue);
editor.putString(AppConstants.PASS_KEY, passValue);
editor.putString("Internet", "true");
editor.putString(AppConstants.ID, id);
editor.putString(AppConstants.PROJECT_NAME, projectName);
editor.putString(String.valueOf(AppConstants.STOCK_POINT), String.valueOf(stockPoint));
editor.commit();
**//Here move to next screen or home screen**
Intent profactivity = new Intent(MainActivity.this, View.class); profactivity.putExtra("Internet", true); profactivity.putExtra("loginValue", loginValue); profactivity.putExtra("id", id);
profactivity.putExtra("projectName", projectName);
profactivity.putExtra("stockPoint", finalList);
startActivity(profactivity);
Toast.makeText(MainActivity.this, "Login Successfully", Toast.LENGTH_LONG).show();
finish();
} else if (statusRes.equalsIgnoreCase("failed")) {
if (!validate()) {
onLoginFailed();
return;
}
}
}
});
}
}).start();
//return data;
} catch (Exception e) {
Log.i("httpget", "################Error1 -->" + e.getStackTrace());
**Toast.makeText(getBaseContext(), "ERROR : " + e.getMessage(), Toast.LENGTH_LONG).show();**
}
} catch (UnsupportedEncodingException ex) {
finish();
}
}
});
}
public boolean validate() {
boolean valid = true;
String email = login.getText().toString();
String passwor = password.getText().toString();
if (email.isEmpty() || email.length() < 2 || email.length() > 10) {
login.setError("enter valid username");
valid = false;
} else {
login.setError("Invalid username");
}
if (passwor.isEmpty() || passwor.length() < 2 || passwor.length() > 10) {
password.setError("enter valid password");
valid = false;
} else {
password.setError("Invalid password");
}
return valid;
}
public void onLoginFailed() {
**Toast.makeText(getBaseContext(), "Invalid login", Toast.LENGTH_LONG).show();**
}
}
--------------------------------------------------------------------------------
The error that you have mentioned says you have error on following line.
projectName = respObject.getString("projectName");
"responseObject" is null, hence you are getting NullPointerException.
I have an ArrayList<String> that I save in shared preference in Activity A. I access the list from a second activity (ListActivity). Activity A starts ListActivity for a result. When an item is clicked the ListActivity sends the string at that position to Activity A for use. A long click allows you to delete.
When I delete from the list, I want to save the new (the latest) list in sharedpreferences. PLEASE! How can I do this? I just need the List to popup, you do your thing, and it goes away after saving the newest list.
I tried so many ways (code is patchwork at this point) but the deleted item persists when I open ListActivity again after deleting the item.
My code is below...
Activity A:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_write);
...
lyricTitle = (AutoCompleteTextView) findViewById(R.id.lyricTitle);
...
lyricTitle.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// load in song when selected from auto-complete list
lyricHolder.setText(openSongFile(lyricTitle.getText().toString()));
}
});
lyricHolder = (EditText) findViewById(R.id.lyricHolder);
newSongBtn = (ImageView) findViewById(R.id.newSongBtn);
newSongBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (areFieldsNull(lyricTitle.getText().toString(),
lyricHolder.getText().toString()))
alertEmpty.show();
else {
/** There is some redundancy within performSave() here */
performSave();
lyricTitle.setText("");
lyricHolder.setText("");
}
}
});
...
findBtn = (Button) findViewById(R.id.findBtn);
findBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent showListIntent = new Intent(getApplicationContext(), pickActivity.class);
startActivityForResult(showListIntent, GET_SONG_CODE);
Log.i("TAG1", "Starting pickActivity.class for result");
}
});
saveBtn = (Button) findViewById(R.id.saveBtn);
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
performSave();
}
});
...
// init sharedPreferences
colorPref = getSharedPreferences(COLOR_PREF, MODE_PRIVATE);
titlePref = getSharedPreferences(TITLE_PREF, MODE_PRIVATE);
externalSDPref = getSharedPreferences(EXTERNAL_SD_PREF, MODE_PRIVATE);
// load defaults of sharedPreferences
titleList = new ArrayList<>();
try {
titleList = (ArrayList<String>) ObjectSerializer
.deserialize(titlePref.getString(TITLE_PREF, ObjectSerializer.serialize(new ArrayList<String>())));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
mSetTitleListAdapter(titleList);
...
} //end onCreate
private void mSetTitleListAdapter(ArrayList<String> List) {
autoCompleteAdapter = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
List
);
lyricTitle.setAdapter(autoCompleteAdapter);
}
...
private boolean areFieldsNull(String title, String song) {
// check if the text fields are empty
return (
title.isEmpty()||
title.equals(" ")||
title.equals(" ")||
song.isEmpty()||
song.equals(" ")||
song.equals(" ")
);
}
private void performSave() {
String title = lyricTitle.getText().toString();
String song = lyricHolder.getText().toString();
if(!areFieldsNull(title, song)) {
saveSongFile(title, song);
alertSave.show();
}
else
alertEmpty.show();
}
private void saveTitleArray() {
// save string array list in shared prefs
try {
prefEditor = titlePref.edit();
prefEditor.putString(TITLE_PREF, ObjectSerializer.serialize(titleList));
} catch (IOException e) {
e.printStackTrace();
}
prefEditor.apply();
}
private void saveSongFile(String title, String song) {
BufferedWriter bufferWriter = null;
try {
FileOutputStream fos = openFileOutput(title, Context.MODE_PRIVATE);
bufferWriter = new BufferedWriter(new OutputStreamWriter(fos));
bufferWriter.write(song);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(isExternalStoragePresent()&&externalSD_box.isChecked()){
// save to the SD card IF SD is found AND enableSD_box is checked
File path = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File songFile = new File (path, title + ".txt");
try {
OutputStream os = new FileOutputStream(songFile);
byte[] data = song.getBytes();
os.write(data);
} catch (IOException e) {
e.printStackTrace();
}
}
// new songs (but not updated songs) go to top
if (!titleList.contains(title))
titleList.add(0, title);
mSetTitleListAdapter(titleList);
saveTitleArray();
}
private String openSongFile(String title){
BufferedReader bufferReader = null;
StringBuilder builder = new StringBuilder();
try {
FileInputStream fis = openFileInput(title);
bufferReader = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = bufferReader.readLine()) != null) {
builder.append(line + "\r\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bufferReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return builder.toString();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// when pickActivity ListView returns result
Log.i("TAG1", "Activity data returned from pickActivity.class");
if (requestCode == GET_SONG_CODE && resultCode == RESULT_OK) {
String title = data.getData().toString();
lyricTitle.setText(title);
lyricHolder.setText(openSongFile(title));
Log.i("TAG1", "Result success\nSong loaded into edittext");
Toast.makeText(this, "\""+title+"\""+" selected", Toast.LENGTH_SHORT).show();
}
}
ListActivity:
public class pickActivity extends ListActivity {
ArrayList<String> songListArray;
SharedPreferences titlePref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pick_song);
Log.i("TAG2", "pickActivity.class created");
// init string array from blank list or sharedPref saved data
titlePref = getSharedPreferences(writeActivity.TITLE_PREF, MODE_PRIVATE);
songListArray = new ArrayList<>();
try {
songListArray = (ArrayList<String>) ObjectSerializer
.deserialize(titlePref.getString(writeActivity.TITLE_PREF, ObjectSerializer.serialize(new ArrayList<String>())));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
mSetListAdapter(songListArray);
Log.i("TAG2", "Extra received and set");
mSetListAdapter(songListArray);
getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
Log.i("TAG2", "onItemLongClick()");
final AlertDialog.Builder confirmDel = new AlertDialog.Builder(pickActivity.this);
confirmDel.setTitle("Delete Song")
.setIcon(R.mipmap.ic_keeper)
.setMessage("Are you sure you want " +
"\"" + songListArray.get(position) +
"\"" + " gone?")
.setPositiveButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// system default is dismiss()
}
})
.setNegativeButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// delete song, title, then update title list
getApplicationContext().deleteFile(songListArray.get(position));
songListArray.remove(position);
Log.i("TAG2", "Item deleted from list");
updateSharedPref(titlePref, writeActivity.TITLE_PREF, songListArray);
mSetListAdapter(songListArray);
Toast.makeText(
getApplicationContext(),
"Deleted",
Toast.LENGTH_SHORT).show();
}
});
confirmDel.create().show();
return true;
}
});
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Log.i("TAG2", "onListItemClick()");
Intent resultIntent = new Intent(EXTRA_NAME, Uri.parse(songListArray.get(position)));
setResult(RESULT_OK, resultIntent);
finish();
}
private void mSetListAdapter(ArrayList<String> list) {
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
list
);
setListAdapter(arrayAdapter);
Log.i("TAG2", "ArrayList adapter set");
}
private void updateSharedPref(SharedPreferences sharedPref,
String prefFileName,
ArrayList<String> list) {
SharedPreferences.Editor editor = sharedPref.edit();
try {
editor.putString(prefFileName, ObjectSerializer.serialize(list));
} catch (IOException e) {
e.printStackTrace();
}
editor.commit();
Log.i("TAG2", "SharedPref updated!");
}
}
Honestly, source code would help a lot in this case...
My best guess (without any code) would be, please make sure that you call
editor.apply();
and not
editor.commit();
this is my LoginActivity class, i want to do add remember me option to this class.
public class LoginActivity extends Activity {
ProgressDialog prgDialog;
// Error Msg TextView Object
TextView errorMsg;
// Email Edit View Object
EditText emailET;
// Passwprd Edit View Object
EditText pwdET;
String email;
// Get Password Edit View Value
String password;
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
// Find Error Msg Text View control by ID
errorMsg = (TextView) findViewById(R.id.login_error);
// Find Email Edit View control by ID
emailET = (EditText) findViewById(R.id.txt_email);
// Find Password Edit View control by ID
pwdET = (EditText) findViewById(R.id.txt_pwd);
// Instantiate Progress Dialog object
prgDialog = new ProgressDialog(this);
// Set Progress Dialog Text
prgDialog.setMessage("Please wait...");
// Set Cancelable as False
prgDialog.setCancelable(false);
button = (Button) findViewById(R.id.btlogin);
final Button button = (Button) findViewById(R.id.btlogin);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
// Get Email Edit View Value
String email = emailET.getText().toString();
// Get Password Edit View Value
String password = pwdET.getText().toString();
// When Email Edit View and Password Edit View have values
// other than Null
if (Utility.isNotNull(email) && Utility.isNotNull(password)) {
// When Email entered is Valid
if (Utility.validate(email)) {
new LoginAsyncTask(LoginActivity.this).execute(
email, password);
Toast.makeText(getApplicationContext(),
"Asynctask started", Toast.LENGTH_SHORT)
.show();
}
// When Email is invalid
else {
Toast.makeText(getApplicationContext(),
"Please enter valid email",
Toast.LENGTH_LONG).show();
}
}
// When any of the Edit View control left blank
else {
Toast.makeText(
getApplicationContext(),
"Please fill the form, don't leave any field blank",
Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
}
}
});
TextView registerScreen = (TextView) findViewById(R.id.link_to_register);
// Listening to register new account link
registerScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Switching to Register screen
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
}
});
}
public class LoginAsyncTask extends AsyncTask<String, Integer, JSONObject> {
private JSONObject responseJson = null;
private Context contxt;
private Activity activity;
public LoginAsyncTask(Context context) {
// API = apiURL;
this.contxt = context;
}
// async task to accept string array from context array
#Override
protected JSONObject doInBackground(String... params) {
String path = null;
String response = null;
HashMap<String, String> request = null;
JSONObject requestJson = null;
DefaultHttpClient httpClient = null;
HttpPost httpPost = null;
StringEntity requestString = null;
ResponseHandler<String> responseHandler = null;
// get the username and password
Log.i("Email", params[0]);
Log.i("Password", params[1]);
try {
path = "http://192.168.0.xxx/xxxxxxx/xxxxxx/UserAuthentication";
new URL(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
// set the API request
request = new HashMap<String, String>();
request.put(new String("Email"), params[0]);
request.put(new String("Password"), params[1]);
request.entrySet().iterator();
// Store locations in JSON
requestJson = new JSONObject(request);
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(path);
requestString = new StringEntity(requestJson.toString());
// sets the post request as the resulting string
httpPost.setEntity(requestString);
httpPost.setHeader("Content-type", "application/json");
// Handles the response
responseHandler = new BasicResponseHandler();
response = httpClient.execute(httpPost, responseHandler);
responseJson = new JSONObject(response);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
responseJson = new JSONObject(response);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return responseJson;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
String myResJson;
try {
myResJson = responseJson.getString("status");
String test = myResJson;
if (test.equals("200")) {
Intent intent = new Intent(contxt, ActivityMenu.class);
contxt.startActivity(intent);
} else {
Intent intent = new Intent(contxt, LoginActivity.class);
contxt.startActivity(intent);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
After some research I was able to come up with this code to do the remember me option using shared preference.
public class MainActivity extends Activity {
public static String PREFS_NAME = "mypre";
public static String PREF_EMAIL = "email";
public static String PREF_PASSWORD = "password";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onStart() {
super.onStart();
// read email and password from SharedPreferences
getUser();
}
public void doLogin(View view) {
EditText txtuser = (EditText) findViewById(R.id.txt_user);
EditText txtpwd = (EditText) findViewById(R.id.txt_pwd);
String email = "u";
String password = "p";
if (txtuser.getText().toString().equals(email)
&& txtpwd.getText().toString().equals(password)) {
CheckBox ch = (CheckBox) findViewById(R.id.ch_rememberme);
if (ch.isChecked())
rememberMe(email, password); // save email and password
// show logout activity
showLogout(email);
} else {
Toast.makeText(this, "Invalid email or password", Toast.LENGTH_LONG)
.show();
}
}
public void getUser() {
SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
String email = pref.getString(PREF_EMAIL, null);
String password = pref.getString(PREF_PASSWORD, null);
if (email != null || password != null) {
// directly show logout form
showLogout(email);
}
}
public void rememberMe(String user, String password) {
// save email and password in SharedPreferences
getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit()
.putString(PREF_EMAIL, user).putString(PREF_PASSWORD, password)
.commit();
}
public void showLogout(String email) {
// display log out activity
Intent intent = new Intent(this, ActivityMenu.class);
intent.putExtra("user", email);
startActivity(intent);
}
}
I need help to integrate these 2 classes. I tried but didn't work
this is my out put
public class LoginActivity extends Activity {
ProgressDialog prgDialog;
// Error Msg TextView Object
TextView errorMsg;
// Email Edit View Object
EditText emailET;
// Passwprd Edit View Object
EditText pwdET;
String email;
// Get Password Edit View Value
String password;
Button button;
public static String PREFS_NAME = "mypre";
public static String PREF_EMAIL = "email";
public static String PREF_PASSWORD = "password";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_login);
// Find Error Msg Text View control by ID
errorMsg = (TextView) findViewById(R.id.login_error);
// Find Email Edit View control by ID
emailET = (EditText) findViewById(R.id.txt_user);
// Find Password Edit View control by ID
pwdET = (EditText) findViewById(R.id.txt_pwd);
// Instantiate Progress Dialog object
prgDialog = new ProgressDialog(this);
// Set Progress Dialog Text
prgDialog.setMessage("Please wait...");
// Set Cancelable as False
prgDialog.setCancelable(false);
button = (Button) findViewById(R.id.btlogin);
final Button button = (Button) findViewById(R.id.btlogin);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
// Get Email Edit View Value
String email = emailET.getText().toString();
// Get Password Edit View Value
String password = pwdET.getText().toString();
// When Email Edit View and Password Edit View have values
// other than Null
if (Utility.isNotNull(email) && Utility.isNotNull(password)) {
// When Email entered is Valid
if (Utility.validate(email)) {
if (emailET.getText().toString().equals(email)
&& pwdET.getText().toString()
.equals(password)) {
CheckBox ch = (CheckBox) findViewById(R.id.ch_rememberme);
if (ch.isChecked())
rememberMe(email, password); // save email
// and
// password
// show logout activity
showLogout(email);
}
new LoginAsyncTask(LoginActivity.this).execute(
email, password);
Toast.makeText(getApplicationContext(),
"Asynctask started", Toast.LENGTH_SHORT)
.show();
}
// When Email is invalid
else {
Toast.makeText(getApplicationContext(),
"Please enter valid email",
Toast.LENGTH_LONG).show();
}
}
// When any of the Edit View control left blank
else {
Toast.makeText(
getApplicationContext(),
"Please fill the form, don't leave any field blank",
Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
}
}
});
TextView registerScreen = (TextView) findViewById(R.id.link_to_register);
// Listening to register new account link
registerScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Switching to Register screen
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
}
});
}
public void onStart() {
super.onStart();
// read email and password from SharedPreferences
getUser();
}
public void getUser() {
SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
String email = pref.getString(PREF_EMAIL, null);
String password = pref.getString(PREF_PASSWORD, null);
if (email != null || password != null) {
// directly show logout form
showLogout(email);
}
}
public void rememberMe(String user, String password) {
// save email and password in SharedPreferences
getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit()
.putString(PREF_EMAIL, user).putString(PREF_PASSWORD, password)
.commit();
}
public void showLogout(String email) {
// display log out activity
Intent intent = new Intent(this, ActivityMenu.class);
intent.putExtra("user", email);
startActivity(intent);
}
public class LoginAsyncTask extends AsyncTask<String, Integer, JSONObject> {
private JSONObject responseJson = null;
private Context contxt;
private Activity activity;
public LoginAsyncTask(Context context) {
// API = apiURL;
this.contxt = context;
}
// async task to accept string array from context array
#Override
protected JSONObject doInBackground(String... params) {
String path = null;
String response = null;
HashMap<String, String> request = null;
JSONObject requestJson = null;
DefaultHttpClient httpClient = null;
HttpPost httpPost = null;
StringEntity requestString = null;
ResponseHandler<String> responseHandler = null;
// get the email and password
Log.i("Email", params[0]);
Log.i("Password", params[1]);
try {
path = "http://192.168.0.xxx/xxxxxxxx/xxxxx/UserAuthentication";
new URL(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
// set the API request
request = new HashMap<String, String>();
request.put(new String("Email"), params[0]);
request.put(new String("Password"), params[1]);
request.entrySet().iterator();
// Store locations in JSON
requestJson = new JSONObject(request);
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(path);
requestString = new StringEntity(requestJson.toString());
// sets the post request as the resulting string
httpPost.setEntity(requestString);
httpPost.setHeader("Content-type", "application/json");
// Handles the response
responseHandler = new BasicResponseHandler();
response = httpClient.execute(httpPost, responseHandler);
responseJson = new JSONObject(response);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
responseJson = new JSONObject(response);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return responseJson;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
String myResJson;
try {
myResJson = responseJson.getString("status");
String test = myResJson;
if (test.equals("200")) {
Intent intent = new Intent(contxt, ActivityMenu.class);
contxt.startActivity(intent);
} else {
Intent intent = new Intent(contxt, LoginActivity.class);
contxt.startActivity(intent);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
I tried this: when isSessionValid getDetails directly else facebook.authorize and then getDetails in onActivityResult
public class MainActivity extends Activity {
Facebook facebook = new Facebook("xxxxxxxxxxxxxxxx");
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
private SharedPreferences mPrefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this, new String[] {}, new DialogListener() {
#Override
public void onComplete(Bundle values) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
}
#Override
public void onFacebookError(FacebookError error) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onCancel() {
}
});
}else{
try {
JSONObject json = Util.parseJson(facebook.request("me"));
String facebookID = json.getString("id");
String firstName = json.getString("first_name");
String lastName = json.getString("last_name");
String email = json.getString("email");
String gender = json.getString("gender");
} catch (Exception e) {
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
try {
JSONObject json = Util.parseJson(facebook.request("me"));
String facebookID = json.getString("id");
String firstName = json.getString("first_name");
String lastName = json.getString("last_name");
String email = json.getString("email");
String gender = json.getString("gender");
} catch (Exception e) {
}
}
public void onResume() {
super.onResume();
facebook.extendAccessTokenIfNeeded(this, null);
}
}
This works fine when I have facebook app installed on my system. But If not installed i get a Web View to enter facebook credentials and in logcat shows login-success, but none of the getDetails block is called.
Here in initFacebook() function through you can login and perform you functionality, here i am fetching user's friends information.
private void initFacebook()
{
try
{
if (APP_ID == null)
{
Util.showAlert(this,"Warning","Facebook Applicaton ID must be "+ "specified before running this example: see Example.java");
}
mFacebook = new Facebook();
mAsyncRunner = new AsyncFacebookRunner(mFacebook);
mFacebook.authorize(FacebookList.this, APP_ID, new String[] {"email", "read_stream", "user_hometown", "user_location","friends_about_me", "friends_hometown", "friends_location","user_relationships", "friends_relationship_details","friends_birthday", "friends_education_history","friends_website" }, new DialogListener()
{
public void onComplete(Bundle values)
{
getHTTPConnection();
}
public void onFacebookError(FacebookError error)
{
Log.i("public void onFacebookError(FacebookError error)....","....");
}
public void onError(DialogError e)
{
Log.i("public void onError(DialogError e)....", "....");
CustomConfirmOkDialog dialog = new CustomConfirmOkDialog(FacebookList.this, R.style.CustomDialogTheme, Utils.FACEBOOK_CONNECTION_ERROR);
dialog.show();
}
public void onCancel()
{
Log.i("public void onCancel()....", "....");
}
});
SessionStore.restore(mFacebook, this);
SessionEvents.addAuthListener(new SampleAuthListener());
SessionEvents.addLogoutListener(new SampleLogoutListener());
}
catch (Exception e)
{
e.printStackTrace();
}
}
Here in getHTTPConnection(), proceeding for connection and sending fields, that we require about user's friends as here we can see that passing fields are fields=id,first_name,last_name,location,picture of friends. here you can change this fields according to application's requirements.
private void getHTTPConnection()
{
try
{
mAccessToken = mFacebook.getAccessToken();
HttpClient httpclient = new DefaultHttpClient();
String result = null;
HttpGet httpget = new HttpGet("https://graph.facebook.com/me/friends?access_token="+ mAccessToken + "&fields=id,first_name,last_name,location,picture");
HttpResponse response;
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null)
{
result = EntityUtils.toString(entity);
parseJSON(result);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
Now after successfully connecting with facebook , we are getting JSON data and further to parse it .
private void parseJSON(String data1) throws Exception,NullPointerException, JSONException
{
try
{
JSONObject jObj = new JSONObject(data1);
JSONArray jObjArr = jObj.optJSONArray("data");
int lon = jObjArr.length();
for (int i = 0; i < lon; i++)
{
JSONObject tmp = jObjArr.optJSONObject(i);
String temp_image = tmp.getString("picture"); String temp_fname = tmp.getString("first_name");
String temp_lname = tmp.getString("last_name");
String temp_loc = null;
JSONObject loc = tmp.getJSONObject("location");
temp_loc = loc.getString("name");
}
}
catch (Exception e)
{
Log.i("Exception1 is Here>> ", e.toString());
e.printStackTrace();
}
}
It is assumed that you have already added a facebook jar in to your application and for proceeding this code you can call initFacebook() in to onCreate() of your activity
While submitting data from editTexts of Dialog box whose context is in Home activity, the submitted button doing nothing.
host is a button on home activity,when clicked opens up a dialog box in same activity consists of two editText field (ename,eemail) and submit , cancel button. On submit getFeedback() functions called (used from ApiInterface method)
host.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view)
{
final Dialog d=new Dialog(context);
d.setCanceledOnTouchOutside(false);
d.setContentView(R.layout.hostdialog);
d.getWindow().setBackgroundDrawableResource(R.drawable.bgdialog);
final EditText ename=(EditText)d.findViewById(R.id.ename);
final EditText eemail=(EditText)d.findViewById(R.id.eemail);
final Button submit=(Button)d.findViewById(R.id.submit);
final Button clear=(Button)d.findViewById(R.id.clear);
submit.setOnClickListener(new View.OnClickListener() {
#SuppressLint("WrongConstant")
#Override
public void onClick(View view) {
try {
getFeedbacks(ename.getText().toString(),eemail.getText().toString());
d.dismiss();
Toast t = Toast.makeText(getApplicationContext()," ✓ Thank You, We'll contact you soon",Toast.LENGTH_LONG);
View v = t.getView();
v.setBackgroundResource(R.drawable.clear);
t.show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
d.dismiss();
}
});
d.show();
}
});
and my ApiInterface code is:
#GET("myurl")
Call<JsonElement> getFeedbacks(#Body RequestBody requestBody);
getFeedback method consist of:-
private void getFeedbacks(String user_name, String user_email){
JSONObject paramobject = new JSONObject();
try {
paramobject.put("user_name",user_name);
paramobject.put("user_email",user_email);
} catch (JSONException e) {
e.printStackTrace();
}
RequestBody body = RequestBody.create(MediaType.parse("application/json,charset=utf-8"),paramobject.toString());
Call<JsonElement> call = retrofitAPI.getFeedbacks(body);
call.enqueue(new Callback<JsonElement>() {
#Override
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
try {
JSONArray jsonArray = new JSONArray(response.body().toString());
JSONObject jsonObject = new JSONObject();
for (int n = 0; n < jsonArray.length(); n++){
jsonObject = jsonArray.getJSONObject(n);
String successval = jsonObject.optString("success");
if(successval.equals("0")){
Toast t=Toast.makeText(getApplicationContext()," Request Failed, Try Again",Toast.LENGTH_LONG);
View v=t.getView();
v.setBackgroundResource(R.drawable.clear);
t.show();
}else {
Toast t=Toast.makeText(getApplicationContext()," ✓ Thank You, We'll contact you soon",Toast.LENGTH_LONG);
View v=t.getView();
v.setBackgroundResource(R.drawable.clear);
t.show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<JsonElement> call, Throwable t) {
Toast.makeText(Home.this,"Error,Try Again",Toast.LENGTH_LONG).show();
}
});
}
Button does not works. Please provide appropriate solution.
now i alter a little bit code as i change the call anonymously within method. but again no work
host.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Dialog d = new Dialog(context);
d.setCanceledOnTouchOutside(false);
d.setContentView(R.layout.hostdialog);
d.getWindow().setBackgroundDrawableResource(R.drawable.bgdialog);
final EditText ename = (EditText) d.findViewById(R.id.ename);
final EditText eemail = (EditText) d.findViewById(R.id.eemail);
final Button submit = (Button) d.findViewById(R.id.submit);
final Button clear = (Button) d.findViewById(R.id.clear);
submit.setOnClickListener(new View.OnClickListener() {
#SuppressLint("WrongConstant")
#Override
public void onClick(View view) {
try {
sendDataToServer();
d.dismiss();
Toast t = Toast.makeText(getApplicationContext(), " ✓ Thank You, We'll contact you soon", Toast.LENGTH_LONG);
View v = t.getView();
v.setBackgroundResource(R.drawable.clear);
t.show();
} catch (Exception e) {
e.printStackTrace();
}
}
private void sendDataToServer() {
JSONObject paramobject = new JSONObject();
try {
paramobject.put("comment", ename);
paramobject.put("email", eemail);
} catch (JSONException e) {
e.printStackTrace();
}
RequestBody body = RequestBody.create(MediaType.parse("application/json,charset=utf-8"), paramobject.toString());
Call<JsonElement> call = retrofitAPI.getFuturehosts((RequestBody) body);
call.enqueue(new Callback<JsonElement>() {
#Override
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
try {
JSONArray jsonArray = new JSONArray(response.body().toString());
JSONObject jsonObject = new JSONObject();
for (int n = 0; n < jsonArray.length(); n++) {
jsonObject = jsonArray.getJSONObject(n);
String successval = jsonObject.optString("success");
if (successval.equals("0")) {
Toast t = Toast.makeText(getApplicationContext(), " Request Failed, Try Again", Toast.LENGTH_LONG);
View v = t.getView();
v.setBackgroundResource(R.drawable.clear);
t.show();
} else {
Toast t = Toast.makeText(getApplicationContext(), " ✓ Thank You, We'll contact you soon", Toast.LENGTH_LONG);
View v = t.getView();
v.setBackgroundResource(R.drawable.clear);
t.show();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<JsonElement> call, Throwable t) {
Toast.makeText(Home.this, "Error,Try Again", Toast.LENGTH_LONG).show();
}
});
}
});
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
d.dismiss();
}
});
d.show();
}
});
Check your hostdialog.xml file
-button id is "submit" or not
may be that id is diffrent so the code is not working