I'm want to make User register system.. I'm using Facebook SDK and I can send user information my Database from comes to Facebook and successfully registered. But I want to show different fragment activity after this.
If user access my application on Facebook, I'm sending users data Async Class (different class not inner class)
In the summary when my server return the Json data I want to close MainFragmentActivity class and open StartFragmentActivity
I couldn't do it in onPostExecute function with Intent. How can I do it ?
Thanks for help and I'm sorry my poor English
private void makeRequest(final Session session){
Log.d("deneme","makeRequest ÇALIŞIYOR");
Request request = Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if(session == Session.getActiveSession()){
if(user != null){
new MyAsyncTask(getActivity(), "ssoLR", user.getName(),
user.getId(), user.getProperty("email")
.toString());
}
}
}
});
request.executeAsync();
}
My AsyncTask Class like this,
public class MyAsyncTask extends AsyncTask<String, Integer, Double> {
public MyAsyncTask(FragmentActivity a, String tag, String username, String password, String email){
this.mMain = a;
this.tag = tag;
this.username = username;
this.password = password;
this.email = email;
execute(tag, username, password, email);
}
#Override
protected Double doInBackground(String... params) {
if(tag.equals("ssoLR")){
postData(params[0], params[1], params[2], params[3]);
}
return null;
}
public void postData(String tag, String username, String password, String email) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://<my website");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("tag", tag));
nameValuePairs.add(new BasicNameValuePair("name", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
nameValuePairs.add(new BasicNameValuePair("email", email));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
protected void onPostExecute(Double result){
try {
InputStream inputStream = response.getEntity().getContent();
InputStreamReader inputstreamreader = new InputStreamReader(inputStream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
stringbuilder = new StringBuilder();
String buffer = null;
while((buffer = bufferedreader.readLine()) != null){
stringbuilder.append(buffer);
}
} catch (IllegalStateException e) {
} catch (IOException e) {
}
}
protected void onProgressUpdate(Integer... progress){
}
HttpResponse response;
StringBuilder stringbuilder;
private String tag, username, password, email;
}
Related
I need to send a string obtained from EditText in android to the PHP to be used as an id to query the database. So, I got the string from EditText as follows:
childIDVal = childID.getText().toString();
Toast.makeText(getApplicationContext(),childIDVal,Toast.LENGTH_LONG).show();
// To do : transfer data to PHP
transferToPhp(childIDVal);
So, what should my transferToPhp() contain? And also the php code is:
<?php
if( isset($_POST["ChildID"]) ) {
$data = json_decode($_POST["ChildID"]);
$data->msg = strrev($data->msg);
echo json_encode($data);
}
Is it okay? I am a newbie to both android and Php, so i need some help right now. Thanks!
I' m offering you to use AsyncTask which reaches PHP file existing in your server using HttpClient:
/*Sending data to PHP and receives success result*/
private class AsyncDataClass extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost(params[0]);
String jsonResults = "";
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
// SENDING PARAMETERS WITH GIVEN NAMES
nameValuePairs.add(new BasicNameValuePair("paramName_1", params[1]));
nameValuePairs.add(new BasicNameValuePair("paramName_2", params[2]));
// ...
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
jsonResults = inputStreamToString(response.getEntity().getContent()).toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jsonResults;
}
// DO SOMETHING BEFORE PHP RESPONSE
#Override
protected void onPreExecute() {
super.onPreExecute();
}
// DO SOMETHING AFTER PHP RESPONSE
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result.equals("") || result.equals(null)){
return;
}
// Json response from PHP
String jsonResult = returnParsedJsonObject(result);
// i.e.
if (jsonResult.equals("some_response") {
// do something
}
}
// READING ANSWER FROM PHP
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = br.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
e.printStackTrace();
}
return answer;
}
}
// GET ALL RETURNED VALUES FROM PHP
private String returnParsedJsonObject(String result){
JSONObject resultObject;
String returnedResult = "0";
try {
resultObject = new JSONObject(result);
returnedResult = resultObject.getString("response");
String value1 = resultObject.getString("value1");
String value2 = resultObject.getString("value2");
//...
// do something with retrieved values
} catch (JSONException e) {
e.printStackTrace();
}
return returnedResult;
}
To send some parameters use:
AsyncDataClass asyncRequestObject = new AsyncDataClass();
asyncRequestObject.execute("server_url", param1, param2,...);
Hope it helps you.
This is my code for Android:
public void SendDataToServer(final String name, final String email, final String password){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String QuickName = name ;
String QuickEmail = email ;
String QuickPassword = password;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("nome", QuickName));
nameValuePairs.add(new BasicNameValuePair("email", QuickEmail));
nameValuePairs.add(new BasicNameValuePair("password", QuickPassword));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(Configs.signup);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "Data Submit Successfully";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d(result, "Value");
try {
JSONObject jo = new JSONObject(result);
String status = jo.optString("status");
if (status.equals("0")) {
Toast.makeText(Signup.this, "Username already exists", Toast.LENGTH_LONG).show();
} else if (status.equals("1")) {
Intent intent = new Intent(Signup.this, Login.class);
startActivity(intent);
Toast.makeText(Signup.this, "Registered successfully", Toast.LENGTH_LONG).show();
Toast.makeText(Signup.this, "Verify your email adress in email received", Toast.LENGTH_SHORT).show();
finish();
} else if (status.equals("2")) {
Toast.makeText(Signup.this, "Failed to Signup", Toast.LENGTH_LONG).show();
}
//}
}catch (JSONException e) {
e.printStackTrace();
}
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(name, email, password);
}
This is the error:
07-21 12:55:35.297 24973-24973/com.futegolo.igomessenger W/System.err:
org.json.JSONException: Value Data of type java.lang.String cannot be
converted to JSONObject
This is my json response
{"status":0}
This is because you are not returning the actual response from service in doInBackground() method. You are returning as
return "Data Submit Successfully"
And when you convert that string in onPostExecute() method obviously that is not valid JsonObject
Replace your code after this "HttpEntity entity = response.getEntity();"
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
result= convertStreamToString(instream);
// now you have the string representation of the HTML request
instream.close();
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
And rather returning your hard coded string return result. Hope that helps.
for further reference you can follow below links
https://stackoverflow.com/questions/4457492/how-do-i-use-the-simple-http-client-in-android
Use the code as following:
public void SendDataToServer(final String name, final String email, final String password){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String QuickName = name ;
String QuickEmail = email ;
String QuickPassword = password;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("nome", QuickName));
nameValuePairs.add(new BasicNameValuePair("email", QuickEmail));
nameValuePairs.add(new BasicNameValuePair("password", QuickPassword));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(Configs.signup);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
StringBuffer result= new StringBuffer();
BufferedReader in = new BufferedReader(
new InputStreamReader(entity.getContent()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result.append(inputLine);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
return result.toString();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d(result, "Value");
try {
JSONObject jo = new JSONObject(result);
String status = jo.optString("status");
if (status.equals("0")) {
Toast.makeText(Signup.this, "Username already exists", Toast.LENGTH_LONG).show();
} else if (status.equals("1")) {
Intent intent = new Intent(Signup.this, Login.class);
startActivity(intent);
Toast.makeText(Signup.this, "Registered successfully", Toast.LENGTH_LONG).show();
Toast.makeText(Signup.this, "Verify your email adress in email received", Toast.LENGTH_SHORT).show();
finish();
} else if (status.equals("2")) {
Toast.makeText(Signup.this, "Failed to Signup", Toast.LENGTH_LONG).show();
}
//}
}catch (JSONException e) {
e.printStackTrace();
}
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(name, email, password);
}
Appache has already provided a Util class for that called EntityUtils.
Replace return "Data Submit Successfully" with this code
String responseText = EntityUtils.toString(httpResponse.getEntity());
EntityUtils.consume(httpResponse.getEntity());
return responseText;
I am trying to send request to the server and getting a redirect URL as a response {"redirect url":"http://192.168.1.95"} from the server and again I want to send a request to the redirect URL.
I am getting Error:the Connection to http://192.168.1.95 refusedin android.In iOS it works fine.
Please help me to solve this problem.
private void Signup(final String firstname,final String lastname,String email, String password,String action,String path) {
class SignupAsync extends AsyncTask<String, Void, String>{
// private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
#Override
protected String doInBackground(String... params) {
String fname = params[0];
String lname = params[1];
String email = params[2];
String password = params[3];
String action = params[4];
String finalpath1=params[5];
InputStream is = null;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", email));
nameValuePairs.add(new BasicNameValuePair("firstname", fname));
nameValuePairs.add(new BasicNameValuePair("lastname", lname));
nameValuePairs.add(new BasicNameValuePair("password", password));
nameValuePairs.add(new BasicNameValuePair("_action", action));
String result = null;
String finalpath;
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost=null;
if (finalpath1 != null){
httpPost = new HttpPost(finalpath1);
}
else{
httpPost = new HttpPost("http://192.168.1.122");
}
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response=null;
response = httpClient.execute(httpPost);
HttpEntity entity = null;
entity= response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result){
String finalpath = result;
if(finalpath != null)
{
SignupAsync la1 = new SignupAsync();
la1.execute("firstname","lastname","em#h.n","kkkjpass","REGISTERUSER",finalpath); }
}
}
SignupAsync la = new SignupAsync();
la.execute(firstname,lastname,email,password,action,path);
}
i have wrote a method to send some data to server and receive a integer value :
private void sendOrder(Order order,String cid) {
InputStream inputStream = null;
String result = "";
int statusCode = 0;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(send_url);
JSONArray jsonArray = new JSONArray();
for (OrderDetails detail : order.getOrders()) {
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("c_id", cid);
jsonObject.accumulate("r_id", String.valueOf(detail.getR_id()));
jsonObject.accumulate("f_id", String.valueOf(detail.getF_id()));
jsonObject.accumulate("count",
String.valueOf(detail.getCount()));
jsonArray.put(jsonObject);
}
String json = jsonArray.toString();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse httpResponse = httpclient.execute(httpPost);
statusCode = httpResponse.getStatusLine().getStatusCode();
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null)
result = Util.convertInputStreamToString(inputStream);
else
result = "0";
} catch (Exception e) {
Log.d("send order", e.toString());
}
Log.d("order result", result);
return Integer.parseInt(result);
}
the cid is numbers stored in a string like : "30111"
but in the server there is a problem in receiving c_id. its's value in server is like :"c_id":"\"30111\""
i want to c_id to be in the server as same as it is in the client.
how can i fix that ? UPDATE this is my json string in android log :
[{"count":"1","r_id":"8","f_id":"10033","c_id":"\"30111\""},{"count":"2","r_id":"8","f_id":"10034","c_id":"\"30111\""}]
This is my code, working really fine
Make a class -
public class AddQuery extends AsyncTask<Void, Void, Void> {
private Context context;
private ProgressDialog pd;
private String url;
private String jsonResult;
private String qrs;
private String cId;
public AddQuery(Context context, String qrs, String cid) {
// TODO Auto-generated constructor stub
this.context = context;
this.qrs = qrs;
this.cId = cid;
url = "http://" + context.getResources().getString(R.string.url)
+ "/ques.php";
pd = new ProgressDialog(context);
pd.setIndeterminate(true);
pd.setMessage("Retrieving Data..");
pd.setCancelable(false);
}
#Override
protected Void doInBackground(Void... arg0) {
SharedPreferences prefs = context.getSharedPreferences("com.multisoft",
Context.MODE_PRIVATE);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("go", "add"));
params.add(new BasicNameValuePair("qrs", qrs));
params.add(new BasicNameValuePair("cid", cId));
params.add(new BasicNameValuePair("uid", prefs.getString("userID", "0")));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(response.getEntity().getContent())
.toString();
}
catch (ClientProtocolException e) {
Log.e("e", "error1");
e.printStackTrace();
} catch (IOException e) {
Log.e("e", "error2");
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
e.printStackTrace();
Toast.makeText(context, "Error..." + e.toString(),
Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(Void result) {
pd.dismiss();
JSONObject jsonResponse;
jsonResponse = new JSONObject(jsonResult);
//do what you want to do here from text apeared from your php and stored in jsonResult
String c_id = jsonResponse.optString("c_id");
}
execute the above class in your main activity like this-
new AddQuery(MyActivity.this, "4","23").execute();
hi i am trying to check the username and password from mysql database, where i inserted my password using md5() hashing now i wanna access this username, password. i am getting
"org.json.jsonexception end of input at character 1 of"
error.
this is my php code.
<?php
error_reporting(E_ALL^E_NOTICE^E_WARNING);
$dbhost="localhost";
$dbuser="dev";
$dbpass="dev";
$dbdb="myandroid";
$connect =mysql_connect($dbhost,$dbuser,$dbpass) or die("connection error");
mysql_select_db($dbdb) or die("database selection error");
$username=$_POST["username"];
$password=$_POST["password"];
$pass=md5('$password');
$query=mysql_query("SELECT * FROM androidtable WHERE username='$username' AND password='$pass'")or die(mysql_error());
$num=mysql_num_rows($query);
if($num==1){
while($list=mysql_fetch_assoc($query)){
$output=$list;
echo json_encode($output);
}
mysql_close();
}
?>
the android code
public class DBActivity extends Activity implements OnClickListener{
EditText eduser, edpass;
Button logbutton;
String username, password;
HttpClient httpclient;
HttpPost httppost;
ArrayList<NameValuePair> nameValuePair;
HttpResponse httpresponse;
HttpEntity httpentity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_db);
initialise();
}
private void initialise() {
eduser=(EditText) findViewById(R.id.eduser);
edpass=(EditText) findViewById(R.id.edpass);
logbutton=(Button) findViewById(R.id.login);
logbutton.setOnClickListener(this);
}
public void onClick(View v) {
httpclient=new DefaultHttpClient();
httppost=new HttpPost("http://192.168.1.2/androidtut/check.php");
username=eduser.getText().toString();
password=edpass.getText().toString();
try{
nameValuePair=new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("username", username));
nameValuePair.add(new BasicNameValuePair("password", password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
httpresponse=httpclient.execute(httppost);
if(httpresponse.getStatusLine().getStatusCode()==200){
httpentity=httpresponse.getEntity();
if(httpentity != null){
InputStream is=httpentity.getContent();
JSONObject jresp=new JSONObject(convertStreamToString(is));
String retUser=jresp.getString("username");
String retPass=jresp.getString("password");
if(username.equals(retUser) && password.equals(retPass)){
SharedPreferences sp=getSharedPreferences("tableandroid",0);
SharedPreferences.Editor spedit=sp.edit();
spedit.putString("username", username);
spedit.putString("password", password);
spedit.commit();
Toast.makeText(getBaseContext(), "loggin success",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getBaseContext(), "user invalid",Toast.LENGTH_LONG).show();
}
}
}
}catch(Exception e){
String error=e.toString();
Toast.makeText(getBaseContext(), error,Toast.LENGTH_LONG).show();
}
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
Your server isn't returning anything. So your Android client has nothing to marshall.
$pass=md5('$password');
Isn't hashing the password, but the $password string literal instead (single quotes don't expand variables). Use the following instead:
$pass=md5($password);