Java Android - AsyncTask onPostExecute Not getting called - java

So I have been trying to workout an authentication system for my app. I have a REST API running, which is tested to work with Oauth2 authentication using CURL from my laptop, so that I can get tokens for the API.
My result variable within the doInBackground does get a JSON response from my API, giving the access token information, its life, etc.
Like I get this value in result when I debug:
{"access_token":"4Oq6o8oAGRf4oflu3hrbsy18qeIfG1","expires_in":36000,"token_type":"Bearer","scope":"read write","refresh_token":"iocSNJ2PTVbph2RnWmcf0Zv69PDKjw"}
However, my onPostExecute for some reason is not getting called.
Here is my code.
login.java
public class Login extends AppCompatActivity {
Button LoginButton, RegButton;
EditText uUserName, uPassWord;
WSAdapter.SendAPIRequests AuthHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//SetupHomeBtn = (ImageButton) findViewById(R.id.SetupHomeBtn);
LoginButton = (Button) findViewById(R.id.LoginButton);
RegButton = (Button) findViewById(R.id.LoginRegister);
uUserName = (EditText) findViewById(R.id.LoginUserBox);
uPassWord = (EditText) findViewById(R.id.LoginPassBox);
//AuthHelper = new WSAdapter().new SendDeviceDetails();
// Moves user to the main page after validation
LoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// gets the username and password from the EditText
String strUserName = uUserName.getText().toString();
String strPassWord = uPassWord.getText().toString();
// API url duh
String APIUrl = "http://192.168.0.18:8000/auth/token/";
// If the user is authenticated, then transfer to the MainActivity page
if (APIAuthentication(strUserName, strPassWord, APIUrl)){
startActivity(new Intent(Login.this, Posts.class));
}
}
});
RegButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// gets the username and password from the EditText
startActivity(new Intent(Login.this, Register.class));
}
});
}
private boolean APIAuthentication(String un, String pw, String url){
// when it wasn't static -> AuthHelper = new WSAdapter().new SendAPIRequests();
AuthHelper = new WSAdapter.SendAPIRequests();
try {
// Putting the data to be posted in the Django API
AuthHelper.execute(un, pw, url);
return true;
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
}
WSAdapter.java
public class WSAdapter {
static public class SendAPIRequests extends AsyncTask<String, String, String> {
// Add a pre-execute thing
#Override
protected String doInBackground(String... params) {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
Log.e("TAG", params[0]);
Log.e("TAG", params[1]);
//String data = "";
StringBuilder result = new StringBuilder();
HttpURLConnection httpURLConnection = null;
try {
// Sets up connection to the URL (params[0] from .execute in "login")
httpURLConnection = (HttpURLConnection) new URL(params[2]).openConnection();
// Sets the request method for the URL
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
httpURLConnection.setRequestProperty("Accept","application/json");
// Tells the URL that I am sending a POST request body
httpURLConnection.setDoOutput(true);
// Tells the URL that I want to read the response data
httpURLConnection.setDoInput(true);
// JSON object for the REST API
JSONObject jsonParam = new JSONObject();
jsonParam.put("client_id", "mYIHBd321Et3sgn7DqB8urnyrMDwzDeIJxd8eCCE");
jsonParam.put("client_secret", "qkFYdlvikU4kfhSMBoLNsGleS2HNVHcPqaspCDR0Wdrdex5dHyiFHPXctedNjugnoTq8Ayx7D3v1C1pHeqyPh1BjRlBTQiJYSuH6pi9EVeuyjovxacauGVeGdsBOkHI3");
jsonParam.put("username", params[0]);
jsonParam.put("password", params[1]);
jsonParam.put("grant_type", "password");
Log.i("JSON", jsonParam.toString());
// To write primitive Java data types to an output stream in a portable way
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
// Writes out a byte to the underlying output stream of the data posted from .execute function
wr.writeBytes(jsonParam.toString());
// Flushes the jsonParam to the output stream
wr.flush();
wr.close();
// // Representing the input stream
InputStream in = new BufferedInputStream(httpURLConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
// reading the input stream / response from the url
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Disconnects socket after using
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
Log.e("TAG", result.toString());
return result.toString();
}
#Override
protected void onPostExecute(String result) {
//super.onPostExecute(result);
// expecting a response code fro my server upon receiving the POST data
Log.e("TAG", result);
}
}

SO I actually just figured this out. It turns out that my code is running fine, its just that when I debug, I didn't realize theres a button to the side "Run the new thread" or something like that. It then sent me to the onPostExecute. Sorry for being a noob. Hopefully this can be a help to somebody in the future with this simple mistake.

Related

Trying to redirect the user to new page after login in android studio

I'm having problem with redirecting user to new page after the login authentication. If I try to direct my next page in postexecute method it works with
Intent home = new Intent(context,Home_page.class);
context.startActivity(home);
but then it directs it to next page even if the login credentials are wrong. How do i modify my code so that it first check the login credentials and then links the next page with login button.
class background_login extends AsyncTask<String, Void,String>
{
AlertDialog dialog;
Context context;
public background_login (Context context)
{
this.context = context;
}
#Override
protected void onPreExecute() {
dialog = new AlertDialog.Builder(context).create();
dialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String s) {
dialog.setMessage(s);
dialog.show();
}
#Override
protected String doInBackground(String... params)
{
String results="";
String user_name = params[0];
String password = params[1];
String connstr= "url";
try
{
URL url= new URL(connstr);
HttpURLConnection http =(HttpURLConnection) url.openConnection();
http.setRequestMethod("POST");
http.setDoInput(true);
http.setDoOutput(true);
OutputStream ops = http.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(ops,"UTF-8" ));
String data = URLEncoder.encode("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8")
+"&&"+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
writer.write(data);
writer.flush();
writer.close();
ops.close();
InputStream ips = http.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(ips, "ISO-8859-1"));
String line ="";
while ((line = reader.readLine()) !=null)
{
results+=line;
}
reader.close();
ips.close();
http.disconnect();
return results;
} catch (MalformedURLException e) {
results= e.getMessage();
} catch (IOException e) {
results=e.getMessage();
}
return results;
}
}
In onPostExecute you should check request response data like json, xml etc. and than call specific activity or provide error message.
AsyncTask json example: Get JSON in AsyncTask Android
#Override
protected void onPostExecute(JSONObject jsonData){
try {
boolean login = jsonData.getBoolean('isLoginSuccess');
if(login){
String keyToAccessLater = jsonData.getString('accessKey');
Intent home = new Intent(((Activity)context), Home_page.class);
((Activity)context).startActivity(home);
else
...
...
}

How to parse data from json(url) and send data to url

I am trying to send data to url from where i am parsing json data and i want to know can we edit json data in url if we created random json store from myjson.com or we have to maintain our own server to edit json data.Here i created random json store and i am parsing data from that url and i also wanted to edit the data in url thats the problem i was not able to do .Its not working.please help???
This was structure
[{"name":"pavan","hit":true}]
this was mainactivity code from where fetchdata executes in background
public class MainActivity extends AppCompatActivity {
Button click;
public static TextView data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
click=(Button)findViewById(R.id.button);
data=(TextView)findViewById(R.id.fetcheddata);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fetchdata process=new fetchdata();
process.execute();
}
});
}
}
This is fetchdata class from where fetching data from url and displaying in text view of mainactivity
public class fetchdata extends AsyncTask<Void,Void,Void> {
String data="";
String dataparsed="";
String singleparsed="";
boolean flag=false;
#Override
protected Void doInBackground(Void... params) {
try {
URL url=new URL("https://api.myjson.com/bins/1854yb");
HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
InputStream inputStream=httpURLConnection.getInputStream();
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
String line="";
while (line!=null)
{
line=bufferedReader.readLine();
data=data+line;
}
JSONArray JA=new JSONArray(data);
for(int i=0;i<JA.length();i++)
{
JSONObject JO= (JSONObject) JA.get(i);
singleparsed="Name:"+JO.get("name")+"\n"+"Feed key:"+JO.get("hit");
dataparsed=dataparsed+singleparsed;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
MainActivity.data.setText(this.dataparsed);
JSONObject postData = new JSONObject();
try {
postData.put("name","sai");
postData.put("hit", false);
new senddata().execute("https://api.myjson.com/bins/1854yb", postData.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This is senddata to url code from postexecute of fetchdata this was executing and nothing is happening in url please help i am working on this from 3 days
public class senddata extends AsyncTask<String,Void, String> {
String data="";
String dataparsed="";
String singleparsed="";
boolean flag=false;
#Override
protected String doInBackground(String... params) {
String data = "";
HttpURLConnection httpURLConnection = null;
try {
httpURLConnection = (HttpURLConnection) new URL(params[0]).openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes("PostData=" + params[1]);
wr.flush();
wr.close();
InputStream in = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(in);
int inputStreamData = inputStreamReader.read();
while (inputStreamData != -1) {
char current = (char) inputStreamData;
inputStreamData = inputStreamReader.read();
data += current;
}
dataparsed=data;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.e("TAG", result);
}
}
This api doesn't accept any paramter after its url.
It is a get method Api url not post method . Try running it in post method in postman , it will give error.
If u run in get method ,it will produce same output ,even if u add something after url :-"https://api.myjson.com/bins/1854yb"
I think you have some issue with myJson in creating api. If you are a beginner in android your can also try with Link for ready made Api for Android
They have created different kind of Apis for understanding the json concept.
also get some update about PostMan Link for postman

Where should I put my AsyncTask class for my app?

So I have been trying to make a feature in my app where I can login and then fetch data from my database through the Django REST Framework. My logging in works as it only uses POST, but retrieving items does not work.
For some reason my AsyncTask does not get called for retrieving posts.
I have placed my AsyncTask for both activities, which are login and posts, on a separate java file only for handling Web Server stuff.
I am wondering if this is because I should put AsyncTask on each activities.
login.java
public class Login extends AppCompatActivity {
Button LoginButton;
EditText uUserName, uPassWord;
WSAdapter.SendAPIRequests AuthHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//SetupHomeBtn = (ImageButton) findViewById(R.id.SetupHomeBtn);
LoginButton = (Button) findViewById(R.id.LoginButton);
uUserName = (EditText) findViewById(R.id.LoginUserBox);
uPassWord = (EditText) findViewById(R.id.LoginPassBox);
//AuthHelper = new WSAdapter().new SendDeviceDetails();
// Moves user to the main page after validation
LoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// gets the username and password from the EditText
String strUserName = uUserName.getText().toString();
String strPassWord = uPassWord.getText().toString();
// API url duh
String APIUrl = "http://192.168.0.18:8000/token-auth/";
// If the user is authenticated, then transfer to the MainActivity page
if (APIAuthentication(strUserName, strPassWord, APIUrl)){
startActivity(new Intent(Login.this, Posts.class));
}
}
});
}
private boolean APIAuthentication(String un, String pw, String url){
// when it wasn't static -> AuthHelper = new WSAdapter().new SendAPIRequests();
AuthHelper = new WSAdapter.SendAPIRequests();
JSONObject postData = new JSONObject();
try {
// Attempt to input info to the Django API
postData.put("username", un);
postData.put("password", pw);
// Putting the data to be posted in the Django API
AuthHelper.execute(url, postData.toString());
return true;
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
}
posts.java
public class Posts extends AppCompatActivity {
TextView postsSect;
Button postsDoneBtn;
WSAdapter.SendAPIRequests PostsHelper;
StringBuilder postsBuffer = new StringBuilder();
#Override
protected void onResume(){
super.onResume();
PostsDetails postDetailsHelper = new PostsDetails();
postDetailsHelper.ListPosts();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_posts);
PostsDetails postDetailsHelper = new PostsDetails();
postsDoneBtn = (Button) findViewById(R.id.PostsDoneButton);
postDetailsHelper.callPostDetails("192.168.0.18:8000/api");
postDetailsHelper.ListPosts();
postDetailsHelper.postDetailsCalled('n');
postsDoneBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Posts.this, MainActivity.class));
}
});
}
public class PostsDetails {
//String post_title, post_content;
ArrayList<Integer> post_id = new ArrayList<Integer>();
ArrayList<String> post_title = new ArrayList<String>();
ArrayList<String> post_content = new ArrayList<String>();
boolean isPDCalled;
// sets if Post details are called
boolean postDetailsCalled(char called) {
if (called == 'y'){
return true;
}
return false;
}
// checks if postsDetails functions are called for AsyncTask
boolean getIsPDCalled(){
return isPDCalled;
}
// calls the execute for AsyncTask
private void callPostDetails(String theurl){
PostsHelper = new WSAdapter.SendAPIRequests();
// sets if post details are called
postDetailsCalled('y');
// executes AsyncTask
PostsHelper.execute(theurl);
}
// sets values for the posts arrays
public void setPost(int p_id, String p_title, String p_content) {
post_id.add(p_id);
post_title.add(p_title);
post_content.add(p_content);
}
// Lists the posts from the database
public void ListPosts() {
/////////// add functionality if a post was deleted and was clicked
postsSect = (TextView) findViewById(R.id.PostsSection);
postsSect.setText(post_title.get(post_title.size()) + "\n");
for (int i = post_id.size() - 1; i > 0; i--)
{
postsSect.append(post_title.get(i));
}
}
}
}
WSAdapter.java
// I forgot what WS stands for, but this class serves as an adapter for JSON and Online stuff
// I think it stands for With-Server Adapter
public class WSAdapter extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
static public class SendAPIRequests extends AsyncTask<String, String, String> {
// Add a pre-execute thing
#Override
protected String doInBackground(String... params) {
Log.e("TAG", params[0]);
Log.e("TAG", params[1]);
String data = "";
HttpURLConnection httpURLConnection = null;
try {
// Sets up connection to the URL (params[0] from .execute in "login")
httpURLConnection = (HttpURLConnection) new URL(params[0]).openConnection();
// Sets the request method for the URL
httpURLConnection.setRequestMethod("POST");
// Tells the URL that I am sending a POST request body
httpURLConnection.setDoOutput(true);
// To write primitive Java data types to an output stream in a portable way
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
// Writes out a byte to the underlying output stream of the data posted from .execute function
wr.writeBytes("postData=" + params[1]);
// Flushes the postData to the output stream
wr.flush();
wr.close();
// Representing the input stream
InputStream in = httpURLConnection.getInputStream();
// Preparing input stream bytes to be decoded to charset
InputStreamReader inputStreamReader = new InputStreamReader(in);
StringBuilder dataBuffer = new StringBuilder();
// Translates input stream bytes to charset
int inputStreamData = inputStreamReader.read();
while (inputStreamData != -1) {
char current = (char) inputStreamData;
inputStreamData = inputStreamReader.read();
// concatenates data characters from input stream
dataBuffer.append(current);
}
data = dataBuffer.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
// Disconnects socket after using
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
Log.e("TAG", data);
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// expecting a response code fro my server upon receiving the POST data
Log.e("TAG", result);
Posts.PostsDetails postsHelper = new Posts().new PostsDetails();
// For posts
try {
if (postsHelper.getIsPDCalled()){
JSONObject pJObj = new JSONObject(result);
JSONArray pJObjArray = pJObj.getJSONArray("posts");
for (int i = 0; i < pJObjArray.length(); i++) {
JSONObject pJObj_data = pJObjArray.getJSONObject(i);
postsHelper.setPost(pJObj_data.getInt("id"), "post_title", "post_content");
}
}
} catch (JSONException e) {
//Toast.makeText(JSonActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Log.d("Json","Exception = "+e.toString());
}
}
}
}
Yes, you can and should put the network calls functions in a separate java file for better readability and test-coverage.
Apart from that, i would suggest to use Retrofit as your HTTP client. It helps you to manage all the dirty things like headers and converters etc, so you can put all your effort on your logic and implementing your callback actions.

Android connecting with MySql using AsyncTask and return data in form of JSON or String

I have been working to connect MySql database to my android app and searched on internet. Some of the solutions worked with one problem. The problem is that the function returns data in the form which is String and the content of String is :
[{"id":1,"username":"admin","password":"root","email":"admin#localhost.com","fullname":"Site Admin"}]
But I want the data in form of some sort of array through which I can get all the user data like email , fullname separately. I tried to implement a function but that didn't work. Following is the code:
BackgroundWorker.java
public class BackgroundWorker extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
String tresult;
BackgroundWorker (Context ctx){
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String username = params[1];
String password = params[2];
String login_url = "http://192.168.1.18/myproj/api/query1.php";
if (type.equals("login")){
try {
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String post_data = URLEncoder.encode("username","UTF-8")+"="+URLEncoder.encode(username,"UTF-8")+"&"+
URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String line="";
String result="";
while((line = bufferedReader.readLine())!= null){
result+=line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
alertDialog.show();
tresult = result;
//return tresult;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
BackgroundWorker is a class which works in background and connect with database. And in MainActivity it is called as following:
MainActivity
public void onLogin(View view, String user, String pass){
String type = "login";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type,user,pass);
}
Calling of function:
loginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String username = user_edittext.getText().toString();
String password = pass_edittext.getText().toString();
onLogin(v,username,password);
}
});
In short I want to return the variable result or tresult from protected void onPostExecute(String result) in my MainActivity and convert it to Array. Thankyou! waiting for experts opinion.
It seems you have two issues:
Converting a Json string to a more friendly format
Returning this friendly format to another activity
on 1:
There is no built in way to parse JSON strings in Java but lots of easy library options available - take a look at How to parse JSON in Java where these are discussed.
on 2:
In general data is converted to a bundle and returned to your main activity as part of the intent system

Displaying tables and colums from online database in Android Studio

I have designed an application with a successful login and register system in Android Studio. I am hosting my DB on hosting24.
I need to pull data from the DB and display it onscreen inside the application.
Can anyone suggest how to? I have a heap of code written for this application so any suggestions of what code is needed to see I will post. I am not too sure what code I would need to post here..
Scenario would be if a teacher logs into the application they will see a list of registered students and corresponding data related to those students.
<?php
$con = mysqli_connect("host", "username", "pw", "db");
$FirstName = $_POST["FirstName"];
$LastName = $_POST["LastName"];
$statement = mysqli_prepare($con, "SELECT * FROM Student");
mysqli_stmt_bind_param($statement, "ss",$FirstName, $LastName);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = false;
while(mysqli_stmt_fetch($statement)){
$response["success"] = true;
$response["FirstName"] = $FirstName;
$response["LastName"] = $LastName;
}
echo json_encode($response);
?>
Here is my java code
public class UserAreaActivity extends AppCompatActivity implements View.OnClickListener{
Button fetch;
TextView text;
EditText et;
HttpURLConnection urlConnection = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_area);
fetch= (Button) findViewById(R.id.fetch); //XML Button to get the data
fetch.setOnClickListener(this);
}
class task extends AsyncTask<String, String, Void>
{
private ProgressDialog progressDialog = new ProgressDialog(UserAreaActivity.this);
InputStream is = null ;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Fetching data...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface arg0) {
task.this.cancel(true);
}
});
}
#Override
protected Void doInBackground(String... params) {
try {
URL url = new URL("MY PHP URL");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
is = urlConnection.getInputStream();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while((line=br.readLine())!=null)
{
sb.append(line+"\n");
}
is.close();
result=sb.toString();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error converting result "+e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
// ambil data dari Json database
try {
JSONArray Jarray = new JSONArray(result);
for(int i=0;i<Jarray.length();i++)
{
JSONObject Jasonobject = null;
Jasonobject = Jarray.getJSONObject(i);
//get an output on the screen
String firstName = Jasonobject.getString("FirstName");
String db_detail="";
if(et.getText().toString().equalsIgnoreCase(firstName)) {
db_detail = Jasonobject.getString("detail");
text.setText(db_detail);
break;
}
}
this.progressDialog.dismiss();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
Result in this is it hangs on fetching data for me. I just need a list of names to print to screen
First you will need to create a server side file which can fetch the data from database and post it as JSON (or other format if you prefer)
<?php
// Code to connect to database
// fetch and process the data
// print json echo json_encode($output)
?>
Suppose the above php file is at http://example.com/process.php
In Android you need to make an asynchronous HTTP request to the JSON API you created earlier (at http://example.com/process.php). One way is to use an AsyncHttpClient to fetch data
public void loadFromWeb(){
RequestParams params = new RequestParams();
AsyncHttpClient client = new AsyncHttpClient();
params.put("parameter", data);
client.post("http://example.com/process.php", params, new JsonHttpResponseHandler() {
#Override
public void onStart() {
}
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
try {
//process the response
//Do what you want with data, display in your layout
} catch (Exception e) {
//catch exception
}
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
// Process failure
}
});
}
You might want to read more about AsyncHttpClient for this.
Or you can have a look at other ways to make asynchronous calls, one such library is RetroFit

Categories