Click here to Skip to main content
15,901,001 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
package com.example.get;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;













import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{
private EditText user;
private Button get;
TextView txtFname;
TextView txtMname;
TextView txtLname;

JSONObject hay;
// Progress Dialog
private ProgressDialog pDialog;

// JSON parser class
JSONParser jsonParser = new JSONParser();


private static final String LOGIN_URL = "http://www.digiassistant.comuf.com/projectphp/test.php"; // change to the webhost

//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/login.php";

//JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//setup input fields
user = (EditText)findViewById(R.id.user);
txtFname = (TextView) findViewById(R.id.fname);
txtMname = (TextView) findViewById(R.id.lname);
txtLname = (TextView) findViewById(R.id.mname);


//setup buttons
get = (Button)findViewById(R.id.get);

//register listeners
get.setOnClickListener(this);



}



@Override
public void onClick(View v) {
// TODO Auto-generated method stub

new AttemptLogin().execute();

}

class AttemptLogin extends AsyncTask<string,> {

/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;

@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Attempt login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}


@Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();


try {
// Building Parameters
List<namevaluepair> params = new ArrayList<namevaluepair>();
params.add(new BasicNameValuePair("username", username));

Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);

// check your log for json response
Log.d("Login attempt", json.toString());

// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());

///

//
//Intent i = new Intent(Login.this, MainActivity.class);

//finish();
//startActivity(i);
//finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);

}
} 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 product deleted
pDialog.dismiss();
try{
JSONObject json = null;
JSONObject hay = new JSONObject ((Map) json);
JSONArray user = hay.getJSONArray("user");
JSONObject jb= user.getJSONObject(0);
String firstname = jb.getString("firstname");
String middlename = jb.getString("middlename");
String lastname = jb.getString("lastname");

// displaying all data in textview

txtFname.setText("Firstname: " + firstname);
txtMname.setText("Middle Name: " + middlename);
txtLname.setText("Last Name " + lastname);
}catch(Exception e)
{
e.printStackTrace();
}
if (file_url != null){
Toast.makeText(MainActivity.this, file_url, Toast.LENGTH_LONG).show();
}

}

}

}

when i run this i get post available only .
it doesnt update the txtviews



here is my php file




require('config.inc.php');


if (!empty($_POST)) {

//initial query
$query = "Select last_name, first_name, middle_initial FROM admin where username = :user";

$query_params = array(':user' => $_POST['username']);

//execute query
try {
$stmt = $db -> prepare($query);
$result = $stmt -> execute($query_params);
} catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}

// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt -> fetchAll();

if ($rows) {
$response["success"] = 1;
$response["message"] = "Post Available!";
$response["user"] = array();

foreach($rows as $row) {
$user = array();
// $user["designation"] = $row["designation"];
$user["middlename"] = $row["middle_initial"];
$user["firstname"] = $row["first_name"];
$user["lastname"] = $row["last_name"];

//update our repsonse JSON data
array_push($response["user"], $user);
}

// echoing JSON response
echo json_encode($response);

} else {
$response["success"] = 0;
$response["message"] = "No user available!";
die(json_encode($response));
}

} else {}


?>

<form action="test.php" method="POST">
Username: <input type="text" name="username">
<input type="submit" value="Submit">
</form>
Posted
Comments
Sergey Alexandrovich Kryukov 19-Nov-14 14:13pm    
Help with what? You need to ask a question, explain some problem. You can only expect help in the form of an answer.
—SA
Member 11062532 20-Nov-14 3:17am    
the textview is not displaying the values i pass . it gives the post available message . but no update in text view
Richard MacCutchan 20-Nov-14 4:44am    
Please format your code properly, and indicate exactly which line(s) cause(s) the problem.

1 solution

Not a great deal of information (no logcat output for example) in the question so the following is, of necessity, a bit speculative. I find it helpful to lard my code with Log.e(tag, message); calls when things aren't behaving as expected. You can always strip them out later.

So do you check logcat to see whether or not the onPostExecute exception handler is being invoked; i.e do you see a stack trace? If you do and it is a null exception then it may be variation on a problem posted a few days ago. See Question: Run java code in android application[^]

Java
protected void onPostExecute(String file_url) {

try{

  // Code cut for clarity

  // Wouldn't be at all surprised to see a null exception thrown here.
  txtFname.setText("Firstname: " + firstname);
  txtMname.setText("Middle Name: " + middlename);
  txtLname.setText("Last Name " + lastname);
  }
catch(Exception e) {
  e.printStackTrace();
  }


If you are getting a null exception then I'd try rearranging the code as below.

Java
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  // Move setup of input fields to onStart override.
}


@Override
protected void onStart() {
  super.onStart();
  // Move code from onCreate() to here.
  // By the time activity has reached this point in its lifecyle we can be 
  // sure that its layout will have finished inflation and any views 
  // therein will be available and we won't have null references.
  user = (EditText)findViewById(R.id.user);
  txtFname = (TextView) findViewById(R.id.fname);
  txtMname = (TextView) findViewById(R.id.lname);
  txtLname = (TextView) findViewById(R.id.mname);

  //setup buttons
  get = (Button)findViewById(R.id.get);

  //register listeners
  get.setOnClickListener(this); 
  }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900