SharedPreferences not reading Data - java

I'm saving two parts of data the users password and username to use at a later data and a random combination of letters to then check when the app is executed again to avoid the login screen again.
I had this working yesterday and for some reason, I expect I misplaced code when adding a feature and now cannot get it working again, I've tried all day to fix it and yet I cannot.
EDIT1: For some reason, it goes to the else statement on the "CheckPrefs" method, which I CANNOT UNDERSTAND.
EDIT2: It saves the preferences fine and goes to the intent but, it just can't read it.
Code:
public static final String PREFS_NAME = "MyPregs";
public static final String PREFS_CHECK = "CheckSignedIn";
public static final String UID ="";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
CheckPrefs();
// Login button clicked
ok = (Button) findViewById(R.id.btn_login);
ok.setOnClickListener(this);
result = (TextView) findViewById(R.id.lbl_result);
}
private void CheckPrefs() {
// TODO Auto-generated method stub
//checks to see if the user has signed in before if they have it gets there data from SharedPreferences and checks against our database via HttpPost.
SharedPreferences settings = getSharedPreferences(PREFS_CHECK, 0);
String SCheck1 = settings.getString("key4", null);
if (SCheck1 != null && equals(UID)) {
Intent c = new Intent(this, CheckUserInfo.class);
startActivity(c);
} else {
}
}
//create bracket.
public void postLoginData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
/* login.php returns true if username and password is equal to saranga */
HttpPost httppost = new HttpPost("http://gta5news.com/login.php");
try {
// Add user name and password
uname = (EditText) findViewById(R.id.txt_username);
String username = uname.getText().toString();
pword = (EditText) findViewById(R.id.txt_password);
String password = pword.getText().toString();
SharedPreferences signedin = getSharedPreferences(PREFS_CHECK, 0);
SharedPreferences.Editor editor1 = signedin.edit();
editor1.putString("key4", UID);
editor1.commit();
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("key1", username);
editor.putString("key2", password);
editor.commit();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
Log.w("HttpPost", "Execute HTTP Post Request");
HttpResponse response = httpclient.execute(httppost);
String str = inputStreamToString(response.getEntity().getContent())
.toString();
Log.w("HttpPost", str);
if (str.toString().equalsIgnoreCase("true")) {
Log.w("HttpPost", "TRUE");
result.setText("Login successful");
try {Thread.sleep(250);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent login = new Intent(LogIn.this, ChatService.class);
startActivity(login);
} else {
Log.w("HttpPost", "FALSE");
result.setText(str);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
public void onClick(View view) {
if (view == ok) {
postLoginData();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(pword.getWindowToken(), 0);
}
// Click end
}
// if statement
}
// class ends here

need to see where you are saving your preferences, so we can match it up with how you're calling your preferences... but, is this a typo?
public static final String PREFS_NAME = "MyPregs";
Should it be "MyPrefs" instead of "MyPregs"?

You have
if (SCheck1 != null && equals(UID))
but do you maybe mean to say
if (SCheck1 != null && !SCheck.equals(UID))
?

You could use the 'reverse comparison' pattern too:
if (UID.equals(SCheck1)) {
} else {
}
This way, you don't have to bother checking SCheck1 == null. UID.equals(null) will return false instead of null.equals(UID) throwing a NullPointerException.

Related

How to handle Login Successful in json? [duplicate]

This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 5 years ago.
I am trying to implement login and signup form in Android with the help of JSON using post method. When i signup and enter the details it successfully register and data has been shown in my local host sever and when i login its enter wrong username and password its show incorrect details in toast and enter right details shows login success in toast, but i want when i enter right details its goes to another activity. and enter wrong details shows only toast. Here is the code :-
MainActivity.java
public class MainActivity extends Activity {
public static HashMap<Sound, MediaPlayer> SOUND_MAP=
new HashMap<Sound, MediaPlayer>();
public static int userScore= 0, computerScore=0,
buddyBoxId = 1, computerBoxId = 1;
public static Context CTX;
Button play;
private static final String TAG = "LoginActivity";
String URL = "http://10.0.2.2/test_android/index.php";
JSONParser jsonParser=new JSONParser();
ProgressDialog progressDialog;
TextView register_caption;
AdView adView = null;
private AdView mAdView;
EditText username, password;
Button btnSignIn, btnRegister;
ImageView fb;
int i=0;
private AdRequest adRequest;
InterstitialAd mInterstitialAd;
static MediaPlayer media;
static Handler mediaHandler;
public static int stat=0, totTurn = 0, maxEnd = 100;
public static SharedPreferences configs;
public static SharedPreferences.Editor configuration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
username = (EditText) findViewById(R.id.email);
password = (EditText)findViewById(R.id.passwordd);
btnSignIn = (Button) findViewById(R.id.play);
register_caption = (TextView) findViewById(R.id.register_caption);
fb = (ImageButton) findViewById(R.id.btnfb);
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AttemptLogin attemptLogin = new AttemptLogin();
attemptLogin.execute(username.getText().toString(), password.getText().toString(), "");
}
});
register_caption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent in = new Intent(MainActivity.this,Registration.class);
startActivity(in);
}
});
CTX = getApplicationContext();
configs = CTX. getSharedPreferences("snake_n_ladder", 0);
configuration = configs.edit();
loadConfig();
loadMedia();
}
private class AttemptLogin extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(String... args) {
String email = args[2];
String password = args[1];
String name = args[0];
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", name));
params.add(new BasicNameValuePair("password", password));
if (email.length() > 0)
params.add(new BasicNameValuePair("email", email));
JSONObject json = jsonParser.makeHttpRequest(URL, "POST", params);
return json;
}
protected void onPostExecute(JSONObject result) {
// dismiss the dialog once product deleted
//Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
try {
if (result != null) {
Toast.makeText(getApplicationContext(), result.getString("message"), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Unable to retrieve any data from server", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
JsonParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static JSONArray jArr = null;
static String json = "";
static String error = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
ArrayList<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method.equals("POST")){
// request method is POST
// defaultHttpClient
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
try {
Log.e("API123", " " +convertStreamToString(httpPost.getEntity().getContent()));
Log.e("API123",httpPost.getURI().toString());
} catch (Exception e) {
e.printStackTrace();
}
HttpResponse httpResponse = httpClient.execute(httpPost);
Log.e("API123",""+httpResponse.getStatusLine().getStatusCode());
error= String.valueOf(httpResponse.getStatusLine().getStatusCode());
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method.equals("GET")){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.d("API123",json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
jObj.put("error_code",error);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
private String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
return sb.toString();
}
}
protected void onPostExecute(JSONObject result) {
try {
if (result != null)
{
if(result.getString("message").equals("Successfully logged in"))
{
Intent intent = new Intent(ThisActivity.this,NewActivity.class);
startActivity(intent);
finish();
}
else
{
Toast.makeText(this,"Invalid credentials",Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(getApplicationContext(), "Unable to retrieve any data from
server", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}

Debugging Android App communicating with Servlet on real device

So the scenario is I am trying to debug a simple application on my real device.I am using eclipse to make the application.
Now my application is communicating with a servlet which is on Server and application is running very smoothly in genymotion emulator(not using the emulator provided by eclipse). But when I try to run it in my device it is working perfectly till one activity class,but application is crashing on second activity.
So, after so many searches I am posting this question here. Hope I can find out any solution for this.
This is my Second Activity:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.success);
Intent objIntent = getIntent();
s2 = objIntent.getStringExtra("repname");
findViewsById();
submit.setOnClickListener(this);
}
private void findViewsById() {
submit = (Button) findViewById(R.id.submit);
headerText = (TextView) findViewById(R.id.tv1);
headerText.setVisibility(View.INVISIBLE);
submit2 = (Button) findViewById(R.id.secondSubmit);
submit2.setVisibility(View.INVISIBLE);
t1= (TextView) findViewById(R.id.tvexample1);
t2= (TextView) findViewById(R.id.tvexample2);
submit2.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
//DO SOMETHING! {RUN SOME FUNCTION ... DO CHECKS... ETC}
lviewAdapter.clear();
lviewAdapter.notifyDataSetChanged();
Calendar cal = Calendar.getInstance();
System.out.println("what is from calendar"+cal);
Date currentLocalTime = cal.getTime();
//System.out.println("what is from CurrentLocalTime"+currentLocalTime);
DateFormat date = new SimpleDateFormat("yyyy-MM-dd");
date.setTimeZone(TimeZone.getTimeZone("GMT"));
//System.out.println("what is from date"+date);
String localTime = date.format(currentLocalTime);
//localTime = "2014-08-26";
System.out.println("and result is == " + localTime);
pb.setVisibility(View.VISIBLE);
new MyAsyncTask().execute(localTime,s2);
}
});
pb=(ProgressBar)findViewById(R.id.progressBar1);
pb.setVisibility(View.GONE);
c=this;
}
public void onClick(View view) {
Log.d("1:", "in the onclick");
Calendar cal = Calendar.getInstance();
System.out.println("what is from calendar"+cal);
Date currentLocalTime = cal.getTime();
//System.out.println("what is from CurrentLocalTime"+currentLocalTime);
DateFormat date = new SimpleDateFormat("yyyy-MM-dd");
date.setTimeZone(TimeZone.getTimeZone("GMT"));
//System.out.println("what is from date"+date);
String localTime = date.format(currentLocalTime);
//localTime = "2014-08-26";
System.out.println("and result is == " + localTime);
pb.setVisibility(View.VISIBLE);
new MyAsyncTask().execute(localTime,s2);
}
// #Override
// public void onBackPressed() {
// Log.d("CDA", "onBackPressed Called");
// Intent setIntent = new Intent(Intent.ACTION_MAIN);
// setIntent.addCategory(Intent.CATEGORY_HOME);
// setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// startActivity(setIntent);
// }
private class MyAsyncTask extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
Log.d("tag1","in do in ");
String s=postData(params);
Log.d("tag2","in do in SSS ");
//Printing this 5 th
Log.d("what is s",s);
return s;
}
protected void onPostExecute(String result){
Log.d("on post ","on post execute");
pb.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(),"Appointment Displayed", Toast.LENGTH_SHORT).show();
//Log.d("tag",result);
init(result);
submit.setVisibility(View.GONE);
headerText.setVisibility(View.VISIBLE);
submit2.setVisibility(View.VISIBLE);
}
}
protected void onProgressUpdate(Integer... progress){
pb.setProgress(progress[0]);
}
public String postData(String valueIWantToSend[]) {
String origresponseText="";
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("CurrentDate",valueIWantToSend[0]));
nameValuePairs.add(new BasicNameValuePair("repname", valueIWantToSend[1]));
System.out.println("CurrentDate"+valueIWantToSend[0]);
System.out.println("username"+valueIWantToSend[1]);
exampleString1= valueIWantToSend[0];
exampleString2= valueIWantToSend[1];
HttpClient httpclient = new DefaultHttpClient();
HttpParams params = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(httpclient.getParams(),10000000);
//httppost = new HttpPost("http://192.168.56.1:8080/First/Hello");
httppost = new HttpPost("http://203.199.134.131:8080/First/Hello");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
/* execute */
HttpResponse response = httpclient.execute(httppost);
System.out.println("response from servlet"+response.toString());
origresponseText=readContent(response);
Log.d("response", origresponseText);
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
}
catch (IOException e) {
// TODO Auto-generated catch block
}
//removing unwated "" and other special symbols from response
String responseText = origresponseText.substring(1,origresponseText.length() -2 );
Log.d("Response tag", responseText);
return responseText;
}
// }
String readContent(HttpResponse response)
{
String text = "";
InputStream in =null;
try {
in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
//Log.d("", line);
sb.append(line + "\n");
//Printing this first
// Log.d("", line);
// Log.e("TAGpppp", ">>>>>PRINTING<<<<<");
// Log.e("TAGiiii", in.toString());
}
text = sb.toString();
Log.d("TEXT", text);
}
catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
in.close();
} catch (Exception ex) {
}
}
return text;
}
#SuppressWarnings("deprecation")
public void init(String result) {
System.out.println(result);
t1.setText(exampleString1);
t2.setText(exampleString2);
String response= result + "}";
System.out.println(response);
try {
JSONObject jsonArray = new JSONObject(response);
System.out.println("1:"+jsonArray);
//ArrayList obj1 = new ArrayList();
JSONArray obj1 = jsonArray.getJSONArray("get");
System.out.println("1:"+obj1);
for (int i = 0; i < obj1.length(); i++) {
System.out.println("Length of array"+obj1.length());
JSONObject results = obj1.getJSONObject(i);
System.out.println("2:"+results);
String pcode= results.getString("ProspCustCode");
System.out.println("Prospect code"+pcode);
String date= results.getString("FollowUpDate");
System.out.println("FollowUpDate"+date);
String time= results.getString("FollowUpTime");
System.out.println("FollowUpTime"+time);
String status= results.getString("Status");
System.out.println("Status"+status);
String ftype= results.getString("FollowUpType");
System.out.println("FollowUpType"+ftype);
String ntime= results.getString("NextFollowUpTime");
System.out.println("NextFollowUpTime"+ntime);
String cname= results.getString("ContactPerson");
System.out.println("ContactPerson"+cname);
String desig= results.getString("Designation");
System.out.println("Designation"+desig);
String com= results.getString("Comments");
System.out.println("Comments"+com);
String spoke= results.getString("SpokenTo");
System.out.println("SpokenTo"+spoke);
insertdata(pcode,date,time,status,ftype,ntime,cname,desig,com,spoke);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void insertdata(String PROSPCUSTCODE, String DATE, String TIME,
String STATUS, String FOLLOWUPTYPE, String NEXTFOLLOWUPTIME, String NAME,
String DESIGNATION, String COMMENTS, String SPOKENTO) {
HashMap<String, String> queryValues = new HashMap<String, String>();
queryValues.put("ProspCustCode", PROSPCUSTCODE);
queryValues.put("Date", DATE);
queryValues.put("Time", TIME);
queryValues.put("Status", STATUS);
queryValues.put("FollowUpType", FOLLOWUPTYPE);
queryValues.put("NextFollowUpTime", NEXTFOLLOWUPTIME);
queryValues.put("Name", NAME);
queryValues.put("Designation", DESIGNATION);
queryValues.put("Comments", COMMENTS);
queryValues.put("SpokenTo", SPOKENTO);
controller.insertDeails(queryValues);
//this.callHomeActivity(view);
DBController dbHelper = new DBController(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor cursor = newDB.rawQuery("SELECT * FROM TempFollowUpDetails", null);
if (cursor != null ) {
if (cursor.moveToFirst()) {
do {
System.out.println(cursor.getColumnIndex("ProspCustCode"));
//String ProspCustCode = c.getString(c.getColumnIndex("ProsCustCode"));
String Date = cursor.getString(cursor.getColumnIndex("Date"));
String Time = cursor.getString(cursor.getColumnIndex("Time"));
String Status = cursor.getString(cursor.getColumnIndex("Status"));
String NextFollowUpTime = cursor.getString(cursor.getColumnIndex("NextFollowUpTime"));
Name = cursor.getString(cursor.getColumnIndex("Name"));
System.out.println(cursor.getString(cursor.getColumnIndex("Name")));
String Designation = cursor.getString(cursor.getColumnIndex("Designation"));
String Comments = cursor.getString(cursor.getColumnIndex("Comments"));
String SpokenTo = cursor.getString(cursor.getColumnIndex("SpokenTo"));
String Id = cursor.getString(cursor.getColumnIndex("Id"));
//ProspCustCodeArray.add(ProspCustCode);
DateArray.add(Date);
TimeArray.add(Time);
StatusArray.add(Status);
NextFollowUpTimeArray.add(NextFollowUpTime);
NameArray.add(Name);
DesignationArray.add(Designation);
CommentsArray.add(Comments);
SpokenToArray.add(SpokenTo);
IdArray.add(Id);
}while (cursor.moveToNext());
}
displaylist(IdArray,NameArray);
}
System.out.println("Elements of name array"+NameArray);
System.out.println("Elements of name array"+DateArray);
System.out.println("Elements of name array"+TimeArray);
System.out.println("Elements of name array"+DesignationArray);
System.out.println("Elements of name array"+CommentsArray);
System.out.println("Elements of name array"+IdArray);
//............. For normal listview
}
private void displaylist(ArrayList<String> idArray2,
ArrayList<String> nameArray2) {
// TODO Auto-generated method stub
listView = (ListView) findViewById(R.id.listViewAnimals);
lviewAdapter = new ListCustomAdapter(this, idArray2, nameArray2);
System.out.println("adapter => "+lviewAdapter.getCount());
listView.setAdapter(this.lviewAdapter);
controller.deleteDetails(null);
//... start appointments details activity to show the details on item click listener
this.listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View viewClicked, int position, long id) {
TextView tv1 =(TextView)viewClicked.findViewById(R.id.lblListItem);
Intent intent = new Intent(Success.this, AppointmentDetails.class);
intent.putExtra("name", tv1.getText().toString());
startActivity(intent);
}
}); }
}
This is what my Log cat shows when asynctask is satrting after button click:
D/1:(15416): in the onclick
I/System.out(15416): what is from calendarjava.util.GregorianCalendar[time=1409392501700,areFieldsSet=true,lenient=true,zone=Asia/Calcutta,firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2014,MONTH=7,WEEK_OF_YEAR=35,WEEK_OF_MONTH=5,DAY_OF_MONTH=30,DAY_OF_YEAR=242,DAY_OF_WEEK=7,DAY_OF_WEEK_IN_MONTH=5,AM_PM=1,HOUR=3,HOUR_OF_DAY=15,MINUTE=25,SECOND=1,MILLISECOND=700,ZONE_OFFSET=19800000,DST_OFFSET=0]
I/System.out(15416): and result is == 2014-08-26
D/tag1(15416): in do in
I/System.out(15416): CurrentDate2014-08-26
I/System.out(15416): usernameaditi
I/System.out(15416): [socket][1] connection /203.199.134.131:8080;LocalPort=36598(10000000)
I/System.out(15416): [CDS]connect[/203.199.134.131:8080] tm:10000 D/Posix(15416): [Posix_connect Debug]Process com.example.simplehttpgetservlet :8080
I/System.out(22364): [socket][/192.168.2.73:45340] connected
I/System.out(15416): [CDS]rx timeout:0
W/System.err(15416): rto value is too small
I/System.out(15416): >doSendRequest
I/System.out(15416): <doSendRequest
I/System.out(15416): response from servletorg.apache.http.message.BasicHttpResponse#423611d8
If you use a real device you need to use the real IP of the server. Keep also in mind to open the required ports for your local network and connect your mobile with your local network via WiFi.
I'm not very familar with the secutity of servlets check also that you can connect to the server with a second computer too. (Depending on your configuration it is possible that you cannot access the server from outside of "localhost")

json-parsing errors at run time

I am trying to send some sign up information to a php server from my Android app.
I have two classes: RegisterActivity and JSONParser.
While I'm trying to run this programs there is some errors like this:
Error parsing data org.json.JSONException: Value not of type java.lang.String cannot be converted to JSONObject" and "android.os.AsyncTask$3.done(AsyncTask.java:299)
Here is my code:
RegisterActivity.java
public class RegisterActivity extends Activity {
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText username;
EditText email;
EditText password;
EditText RePass;
private static String url_create_product = "http://oranz.co/pmdtest/index.php";
private static final String TAG_SUCCESS = "sucess";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set View to register.xml
setContentView(R.layout.register);
Button registerscreen=(Button)findViewById(R.id.btnCntnueRegister);
// Listening to Login Screen link
email = (EditText)findViewById(R.id.reg_email);
password =(EditText)findViewById(R.id.reg_password);
username =(EditText)findViewById(R.id.reg_username);
RePass = (EditText)findViewById(R.id.rereg_password);
EditText passwords=(EditText)findViewById(R.id.reg_password);
passwords.setTransformationMethod(new PasswordTransformationMethod());
EditText repasswords = (EditText) findViewById(R.id.rereg_password);
repasswords.setTransformationMethod(new PasswordTransformationMethod());
registerscreen.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0) {
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
if(email.getText().toString().equals("")&&password.getText().toString().equals("")&&username.getText().toString().equals("")&&RePass.getText().toString().equals(""))
{
Toast toast = Toast.makeText(context, "Please Enter a valed data. !", duration);
toast.show();
}
else if(email.getText().toString().equals("")||password.getText().toString().equals("")||username.getText().toString().equals("")||RePass.getText().toString().equals(""))
{
Toast toast = Toast.makeText(context, "Please check any field is blank. !", duration);
toast.show();
}
else if(password.getText().toString().compareTo(RePass.getText().toString())==0)
{
Intent k = new Intent(getApplicationContext(), ContinueRegister.class);
startActivity(k);
new CreateNewUser().execute();
}
else
{
Toast toast = Toast.makeText(context, "Password matching is failed. !", duration);
toast.show();
}
}
});
TextView loginScreen = (TextView) findViewById(R.id.link_to_login);
loginScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent m = new Intent(getApplicationContext(),LoginActivity.class);
startActivity(m);
}
});
}
class CreateNewUser extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(RegisterActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
String Username = username.getText().toString();
String Email = email.getText().toString();
String Password = password.getText().toString();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Username", Username));
params.add(new BasicNameValuePair("Email", Email));
params.add(new BasicNameValuePair("Password",Password));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created user
Intent i = new Intent(getApplicationContext(),FinishSignupActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create user
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
 * After completing background task Dismiss the progress dialog
 * **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
JSONParser.java:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
This is due to the android emulator crash there is no mistakes in the programs.

Android Static functions

I'm wondering how I can access the return statement with a static function. I have a static function with Async and I want to then get the return statement in another class - I know it sounds complex but, I'm sure it's an easy solution.
Login.class
public class LogIn extends Activity {
Button login;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
TextView top = (TextView) findViewById(R.id.textView2);
final EditText user = (EditText) findViewById(R.id.etUser);
final EditText pass = (EditText) findViewById(R.id.etPass);
CheckBox stay = (CheckBox) findViewById(R.id.cBStay);
Button login = (Button) findViewById(R.id.btLogin);
login.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String user1 = user.getText().toString();
String pass1 = pass.getText().toString();
if(user1 !=null &user1.length()>=1 & pass1 !=null &pass1.length()>=1) {
ComHelper.SendLogin(user1, pass1);
}
}
});
}
}
ComHelper.class
public class ComHelper extends AsyncTask<String, Void, String> {
static String adress ="http://gta5news.com/login.php";
String user;
String pass;
public static boolean SendLogin(String user1, String pass1){
String user = user1.toString();
String pass = pass1.toString();
new ComHelper().execute(user1, pass1, adress);
return true;
}
private static StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
// Wrap a BufferedReader around the InputStream
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
// Read response until the end
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Return full string
return total;
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
InputStream inputStream = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost(adress);
try {
/*Add some data with NameValuePairs */
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("user", user));
nameValuePairs.add(new BasicNameValuePair("password", pass));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
/*Execute */
HttpResponse response = httpclient.execute(post);
String str = inputStreamToString(response.getEntity().getContent())
.toString();
Log.w("HttpPost", str);
if (str.toString().equalsIgnoreCase("true"))
return str;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
return null;
}
}
Now, I want to see if ComHelper.SendLogin() returned true/or at least returned something.
EDIT: When the code is executed nothing happens, I guess that's because I'm not doing anything with the return statement.
You want to implement
protected void onPostExecute (Result result)
on your AsyncTask implementation. The result parameter will be whatever you return from the doInBackground method. Since this runs in the UI thread you can modify the UI how you want at that time.
If you want to look at the value, then you need to save the return value of the method in a local variable
if(user1 !=null && user1.length() > 0 && pass1 !=null && pass1.length() > 0)
{
boolean comLogin = ComHelper.SendLogin(user1, pass1);
if(comLogin)
{
//do something
}
}

Android:Username and password login using httppost

I'm using eclipse and have been trying for a while to do login using http request and php script to connect to the server side.
The problem is when i click the login button nothing happens,my guess is there is a problem with the OnClikListener or the data for the textfield is not been send to the server
Here is my code.
public class LogInActivity extends Activity implements OnClickListener
{
Button ok,back,exit;
TextView result;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ok = (Button)findViewById(R.id.btn_login);
ok.setOnClickListener(LogInActivity.this);
result = (TextView)findViewById(R.id.lbl_result);
}
public void postLoginData() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/androidRegistration/login.php");
try {
EditText uname = (EditText)findViewById(R.id.txt_username);
String username = uname.getText().toString();
EditText pword = (EditText)findViewById(R.id.txt_password);
String password = pword.getText().toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.w("LogInActivity", "Execute HTTP Post Request");
HttpResponse response = httpclient.execute(httppost);
String str = inputStreamToString(response.getEntity().getContent()).toString();
Log.w("LogInActivity", str);
if(str.toString().equalsIgnoreCase("true"))
{
Log.w("LogInActivity", "TRUE");
result.setText("Login successful");
}else
{
Log.w("LogInActivity", "FALSE");
result.setText(str);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private StringBuilder inputStreamToString(InputStream is) {
String line = "";
StringBuilder total = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((line = rd.readLine()) != null) {
total.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return total;
}
#Override
public void onClick(View view) {
if(view == ok){
postLoginData();
}
}
}
You should debug to check if the problem is with the onClick or with the HTTP transport.
Inside onClick I personally wouldn't check view like yours. Not sure if it's working or not but I usually use:
if(null != view)switch(view.getId()){
case R.id.btn_login: postLoginData();break;
}
You should try to scope down where the problem is so it's clear what need fixing.
I'd suggest you add Log.d right after you enter onClick to see if the listener is invoke when you click the screen.
Consider using Log.d(TAG, message) statements to debug your code. The logs can be seen using `adb logcat' or eclipse DDMS. This should tell you the flow of your code. You can also debug using breakpoints in eclipse.
Also, do not perform network I/O in the main loop. Its really bad for you users. Consider using an AsyncTask

Categories

Resources