When setting a value in setData the value is OK in String returnDataTab1, but when getId() states it's null. Is the issue staring me in the face.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.widget.Toast;
public class BackgroundTask extends AsyncTask<String,Void,String>
{
Context context;
String dataResponse = "";
String returnDataTab1;
//getter
public String getId()
{
//The system out below shows a value of null although the setData method set it ok.
System.out.println("zzzzzzzzzzzzzzzzzzzzzzzzzzzzz : "+returnDataTab1);
return returnDataTab1;
}
public void setData(String newResult)
{
returnDataTab1=newResult;
System.out.println("zzzzzzzzzzzzzzzzzzzzzzzzzzzzz : "+returnDataTab1);
/// the returnDataTab value is set ok
}
BackgroundTask(Context ctx)
{
this.context = ctx;
}
#Override
protected String doInBackground(String... params)
{
String urlLogin = "";
String task = params[0];
String loginusername="";
String loginpassword="";
if (task.equals("login"))
{
urlLogin = "http://domain/LoginAndRegister-login.php";
loginusername = params[1];
loginpassword = params[2];
//
try
{
URL url = new URL(urlLogin);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
//send the driver number to the database
OutputStream outputStream = httpURLConnection.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream,"UTF-8");
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
String myDatalogin = URLEncoder.encode("identifier_loginEmail","UTF-8")+"="+URLEncoder.encode(loginusername,"UTF-8")
+"&"+URLEncoder.encode("identifier_loginPassword","UTF-8")+"="+URLEncoder.encode(loginpassword,"UTF-8");
bufferedWriter.flush();
bufferedWriter.write(myDatalogin);
bufferedWriter.close();
outputStream.close();
//get response from the database
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
//String dataResponse = "";
String inputLine = "";
while((inputLine = bufferedReader.readLine()) != null)
{
dataResponse += inputLine;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return dataResponse;
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}//end if statement
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values)
{
super.onProgressUpdate(values);
}
/// gets value OK from background task
#Override
protected void onPostExecute(String result)
{
this.setData(result);
}
}
Would appreciate if you guys could take a look and point out the obvious mistake.
This is the code called from a tab
BackgroundTask backgroundTaskLogin = new BackgroundTask(Tab1Activity.this);
backgroundTaskLogin.execute(task,username,password);
String x;
x=backgroundTaskLogin.getId();
Toast.makeText(getApplicationContext(), "Data Response : "+x, Toast.LENGTH_SHORT).show();
The values are set from
protected void onPostExecute(String result)
{
this.setData(result);
// gets result value fine
}
Related
I am writing a currency exchange android app however when the app is run I do not seem to get a response from the API.
API LINK 1) https://restcountries.eu/rest/v2/all
API LINK 2) http://api.fixer.io/latest
MainActivity Code:
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import static java.lang.reflect.Modifier.FINAL;
public class MainActivity extends AppCompatActivity {
//Fill spinner with values from this URL - https://restcountries.eu/rest/v2/all
final String CURRENCY_DATA = "https://restcountries.eu/rest/v2/all";
ArrayList<String> currency_list = new ArrayList();
Button btn;
//The amount entered x's by the curreny exchange rate..
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new downloadData().execute();
new downloadExchangeRate().execute();
}
});
}
public class downloadData extends AsyncTask<String, Void, String> {
String result = "";
#Override
protected String doInBackground(String... strings) {
try {
URL url = new URL(CURRENCY_DATA);
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int data = inputStreamReader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = inputStreamReader.read();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String s) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("currencies");
for (int i =0; i<jsonArray.length(); i++){
currency_list.add(jsonArray.getJSONObject(i).optString("code"));
Log.d("list", currency_list.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
super.onPostExecute(s);
}
}
}
downloadExchangeRate.java code:
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
public class downloadExchangeRate extends AsyncTask<String,Void,String> {
String result = "";
#Override
protected String doInBackground(String... strings) {
final String EXCHANGE_RATE = "http://api.fixer.io/latest";
try {
URL url = new URL(EXCHANGE_RATE);
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int data = inputStreamReader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = inputStreamReader.read();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String s) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(result);
for (int i = 0; i<jsonObject.length(); i++){
ArrayList<String> rates = new ArrayList<>();
rates.add(jsonObject.optString("rates"));
Log.d("list", rates.toString());
}
} catch (JSONException e) {
e.printStackTrace();
}
super.onPostExecute(s);
}
}
Any help is appreciated, I think I am calling the JSON wrong.
Update Code as:
Use StringBuilder for result (Why? See this https://stackoverflow.com/a/14927864/5227589):
StringBuilder result=new StringBuilder();
...
......
result.append(current);
When using String it will take very long time to complete while loop due to use of result += current;: .
When using StringBuilder:
In onPostExecute
JSONArray jsonArray = new JSONArray(result.toString());
for (int i =0; i<jsonArray.length(); i++){
currency_list.add(jsonArray.getJSONObject(i).getJSONArray("currencies").getJSONObject(0).optString("code"));
//Log.d("list", currency_list.toString());
}
Full Code:
public class downloadData extends AsyncTask<String, Void, String> {
StringBuilder result=new StringBuilder();
#Override
protected String doInBackground(String... strings) {
try {
URL url = new URL(CURRENCY_DATA);
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int data = inputStreamReader.read();
char current = (char) data;
Log.i("data",current+"");
while (data != -1) {
current = (char) data;
result.append(current);
data = inputStreamReader.read();
// Log.i("data",current+"");
}
//Log.i("data",result+"");
} catch (IOException e) {
e.printStackTrace();
}
return result.toString();
}
#Override
protected void onPostExecute(String s) {
try {
JSONArray jsonArray = new JSONArray(result.toString());
for (int i =0; i<jsonArray.length(); i++){
currency_list.add(jsonArray.getJSONObject(i).getJSONArray("currencies").getJSONObject(0).optString("code"));
//Log.d("list", currency_list.toString());
}
Log.d("list", currency_list.toString());
} catch (JSONException e) {
e.printStackTrace();
}
super.onPostExecute(s);
}
}
I am currently populating a RrecyclerView from a remote database but wish to only query the database for dates based on a users ID. I have the userID assigned as a global variable on the LoginActivty of the app but I'm not sure where to pass that information to the php page from my DateActivity.
My Code for the DateActivity is as follows:
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class DateActivity extends AppCompatActivity {
public static String globex_num;
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView mRVDateList;
private AdapterDate mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_date);
//Make call to AsyncTask
new AsyncFetch().execute();
}
private class AsyncFetch extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(DateActivity.this);
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
url = new URL("thephpfile.com");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
List<DataDate> data=new ArrayList<>();
pdLoading.dismiss();
try {
JSONArray jsonArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for(int i=0;i<jsonArray.length();i++){
JSONObject json_data = jsonArray.getJSONObject(i);
DataDate dateData = new DataDate();
dateData.date= json_data.getString("date");
data.add(dateData);
}
// Setup and Handover data to recyclerview
mRVDateList = (RecyclerView)findViewById(R.id.dateList);
mAdapter = new AdapterDate(DateActivity.this, data);
mRVDateList.setAdapter(mAdapter);
mRVDateList.setLayoutManager(new LinearLayoutManager(DateActivity.this));
} catch (JSONException e) {
Toast.makeText(DateActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
I solved the problem by passing it though the link.
url = new URL(www.thephpfile.php?userID=" + LoginActivity.userID);
At the start of the php file I did the following:
$userID = $_GET['userID'];
I could retreive data from web with this code:
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick (View v){
new GetMethodDemo().execute("https://maps.googleapis.com/maps/api/directions/json?origin=Breclav&destination=Brno&sensor=false&units=metric&mode=driving");
}
public class GetMethodDemo extends AsyncTask<String , Void ,String> {
String server_response;
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK){
server_response = readStream(urlConnection.getInputStream());
Log.v("CatalogClient", server_response);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("Response", "" + server_response);
}
}
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
} }
I am able to see in debug that I received data like in this link, but I found that I should use code below for selecting only distance from the data I received. Dont know how to combinate these codes together.. I would like to have in textView how far is the distance between two cities from url.
final JSONObject json = new JSONObject(response);
JSONArray routeArray = json.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONArray newTempARr = routes.getJSONArray("legs");
JSONObject newDisTimeOb = newTempARr.getJSONObject(0);
JSONObject distOb = newDisTimeOb.getJSONObject("distance");
JSONObject timeOb = newDisTimeOb.getJSONObject("duration");
Log.i("Diatance :", distOb.getString("text"));
Log.i("Time :", timeOb.getString("text"));
I am not the author of these codes... Thank You
I am trying to start an activity "Display" which is supposed to start only after the user is authenticated (the usernames and passwords are stored in phpmyadmin database)
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class PatLogin extends Activity {
EditText a,b;
String login_name,login_pass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pat_login);
}
public void patbuttonClick(View v) {
if (v.getId() == R.id.patlogin) {
a = (EditText) findViewById(R.id.TFpusername);
b = (EditText) findViewById(R.id.TFppassword);
login_name = a.getText().toString();
login_pass = b.getText().toString();
String method = "login";
BackgroundTask backgroundTask = new BackgroundTask(this);
backgroundTask.execute(method,login_name,login_pass);
//If possible I would like to call the "Display" activity from here but only when the correct username and password is entered.
//If it's not possible to call from here then I would like to know how to call "Display" activity from "BackgrounTask.java".
}
}
}
The BackgroundTask.java is used to authenticate the user (check if the username and password match) through the phpmyadmin database.
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class BackgroundTask extends AsyncTask<String,Void,String> {
AlertDialog alertDialog;
Context ctx;
BackgroundTask(Context ctx)
{
this.ctx =ctx;
}
int flag=0;
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(ctx).create();
alertDialog.setTitle("Login Information....");
}
#Override
protected String doInBackground(String... params) {
String login_url = "http://10.0.2.2/mobidoc/login.php";
String method = params[0];
if(method.equals("login"))
{
String login_name = params[1];
String login_pass = params[2];
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 data = URLEncoder.encode("login_name","UTF-8")+"="+URLEncoder.encode(login_name,"UTF-8")+"&"+
URLEncoder.encode("login_pass","UTF-8")+"="+URLEncoder.encode(login_pass,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String response = "";
String line = "";
while ((line = bufferedReader.readLine())!=null)
{
response+= line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
if(result.equals("Registration Success..."))
{
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
else
{
alertDialog.setMessage(result);
alertDialog.show();
//When I use the following 2 lines of code, It calls the Display activity even if the wrong password is entered. I need a certain condition to be applied.
Intent myIntent = new Intent(ctx, Display.class);
ctx.startActivity(myIntent);
}
}
}
So what I want to do is call an activity named "Display". This activity should be called only when the correct username and password is entered.
I am attaching the php file too, just for reference.
<?php
require "init.php";
$username = $_POST["login_name"];
$password = $_POST["login_pass"];
$password = md5($password);
$sql_query = "select name from pat_info where username like '$username' and password like '$password';";
$result = mysqli_query($con,$sql_query);
if(mysqli_num_rows($result)>0)
{
$row = mysqli_fetch_assoc($result);
$name = $row["name"];
echo "Login Success... Welcome ".$name;}
else{
echo "Login Failed...Try Again.";
}
Ok I got the solution to it. I had to compare the echo of the php file and compare it with "res" which stores the value of "result". The modified "BackgroundTask.java" is below:
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class BackgroundTask extends AsyncTask<String,Void,String> {
AlertDialog alertDialog;
Context ctx;
String res;
BackgroundTask(Context ctx)
{
this.ctx =ctx;
}
int flag=0;
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(ctx).create();
alertDialog.setTitle("Login Information....");
}
#Override
protected String doInBackground(String... params) {
String login_url = "http://10.0.2.2/mobidoc/login.php";
String method = params[0];
if(method.equals("login"))
{
String login_name = params[1];
String login_pass = params[2];
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 data = URLEncoder.encode("login_name","UTF-8")+"="+URLEncoder.encode(login_name,"UTF-8")+"&"+
URLEncoder.encode("login_pass","UTF-8")+"="+URLEncoder.encode(login_pass,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String response = "";
String line = "";
while ((line = bufferedReader.readLine())!=null)
{
response+= line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
//I stored the response in the following String variable (res)
res = response;
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
if(result.equals("Registration Success..."))
{
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
else if(res.equals("Login Failed...Try Again."))
{
alertDialog.setMessage(result);
alertDialog.show();
}
else
{
alertDialog.setMessage(result);
alertDialog.show();
Intent myIntent = new Intent(ctx, Display.class);
ctx.startActivity(myIntent);
}
}
}
i m trying to get response from server and retrieving it using JSON everything is going great without any error but my IF statement is not executing, program is jumping on other execution task, when i debug my app it says that java.lang.string cannot be converted to jsonObject that's why it is not executing it.... i m new in this programming and it is my first application. I hope anyone can help me please. i m attaching my BackgroundTask.java and server response, if anything else is needed please tell me.
BackgroundTask.java:
'package in.co.medimap.www.myfirstapp;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.widget.EditText;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.gson.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
/**
* Created by sony on 29-04-2016.
*/
public class BackgroundTask extends AsyncTask<String,Void,String>
{
String register_url = "http://192.168.42.14/loginapp/register.php";
String login_url = "http://192.168.42.14/loginapp/login.php";
String json;
JSONArray peoples;
Context ctx;
ProgressDialog progressDialog;
Activity activity;
AlertDialog.Builder builder;
public BackgroundTask(Context ctx)
{
this.ctx=ctx;
activity = (Activity)ctx;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
builder = new AlertDialog.Builder(activity);
progressDialog = new ProgressDialog(ctx);
progressDialog.setTitle("Please Wait");
progressDialog.setMessage("Connecting to server .... ");
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... params)
{
String method = params[0];
if (method.equals("register")) {
try
{
URL url = new URL(register_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 owner_name = params[1];
String shop_name = params[2];
String phone_no = params[3];
String shop_address=params[4];
String password=params[5];
String data = URLEncoder.encode("owner_name","UTF-8")+"="+URLEncoder.encode(owner_name,"UTF-8")+"&"+
URLEncoder.encode("shop_name","UTF-8")+"="+URLEncoder.encode(shop_name,"UTF-8")+"&"+
URLEncoder.encode("phone_no","UTF-8")+"="+URLEncoder.encode(phone_no,"UTF-8")+"&"+
URLEncoder.encode("shop_address","UTF-8")+"="+URLEncoder.encode(shop_address,"UTF-8")+"&"+
URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line = "";
while ((line=bufferedReader.readLine())!=null)
{
stringBuilder.append(line+"\n");
}
httpURLConnection.disconnect();
Thread.sleep(5000);
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else if(method.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 phone_no,password;
phone_no=params[1];
password=params[2];
String data =URLEncoder.encode("phone_no","UTF-8")+"="+URLEncoder.encode(phone_no,"UTF-8")+"&"+
URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line="";
while ((line=bufferedReader.readLine())!=null)
{
stringBuilder.append(line+"\n");
}
httpURLConnection.disconnect();
Thread.sleep(5000);
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String json)
{
progressDialog.dismiss();
try
{
JSONObject jsonObject = new JSONObject(json);
peoples = jsonObject.getJSONArray("server_response");
JSONObject JO = peoples.getJSONObject(0);
String code = JO.getString("code");
String message = JO.getString("message");
//problem starts from here
if (code.equals("reg_true"))
{
showDialog("Registration Success", code, message);
}
else if (code.equals("reg_false")) {
showDialog("Registration Failed", code, message);
}
else if (code.equals("login_true")) {
Intent intent = new Intent(activity, HomeActivity.class);
intent.putExtra("message", message);
activitcode.equals("login_false")) {
showDialog("Login Error...",code, message);
}
}
//IF statement is not executing due to java.lang.string cannot be converted into jsonObject
} catch (JSONException e) {
e.printStackTrace();
}
}
public void showDialog(String title, String code, String message)
{
builder.setTitle(title);
if(code.equals("reg_true")||code.equals("reg_false"))
{
builder.setMessage(message);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
activity.finish();
}
});
}
else if (code.equals("login_false")) {
builder.setMessage(message);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
EditText phone_no, password;
phone_no = (EditText) activity.findViewById(R.id.phone_no);
password = (EditText) activity.findViewById(R.id.password);
phone_no.setText("");
password.setText("");
dialog.dismiss();
}
});
}
AlertDialog alertDialog =builder.create();
alertDialog.show();
}
}
//server response for registration success
{"server_response":[{"code":"reg_true","0":"message=>Registration Success...Thank you....."}]}
i made a similar application and this worked me. Hope this helps
JSONException: Value of type java.lang.String cannot be converted to JSONObject