I am communicating with a database in php mysql travez to display results in a ListView, but I'm trying to implement a ExeptionConnection for when 3G or WIFI but the application can not connect, return to previous Activity and show a Toast. but not how to implement it in my code, I could only implement JsonExeption.
This is my code:
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_list_rs, "GET",
params);
Log.d("All Products: ", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
daftar_rs = json.getJSONArray(TAG_DAFTAR_RS);
for (int i = 0; i < list_rs.length(); i++) {
JSONObject c = list_rs.getJSONObject(i);
//Process Code
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Where url_list_rs is the url of my php. Where I can Implement ExeptionConnection? Can anyone help? Thank Masters!
If you want to create you own exception, you can do:
//create a new Exception class
public class ConnectionException extends Exception {
public ConnectionException(String message){
super(message);
}
}
In your makeHttpRequest method
if(no connection) { //check connection
throw new ConnectionException ("No connection!");
} else { ... }
Finally, and try-catch block
try {
JSONObject json = jParser.makeHttpRequest(url_list_rs, "GET",
params);
catch(ConnectionException ex) {
ex.printStackTrace();
}
Note: I am not sure if this is the best practice.
Related
// I have already jSON file when i called this method its given null value on it.
new load_customername().execute();
Use this method to call below class
public class load_customername extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... args) {
//String i = args[0];
List<NameValuePair> params = new ArrayList<NameValuePair>();
// params.add(new BasicNameValuePair(TAG_Customer_Name, i));
JSONObject json = jParser.makeHttpRequest(url_get_customername, "GET", params);
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
}
AsyncTask runs in worker thread, you won't get response instantly. Use onPostExecute with callBack to read the response.
The code below tested on LG G3 and it worked fine. However when I tested it on a Samsung Galaxy S3/S2 doInBackground() is not called for some reason.
Code to check api:
public void startBlat(String tosearch) {
AsynctaskMovie asynctaskMovie = new AsynctaskMovie();
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB) {
asynctaskMovie.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,tosearch);
}
else {
asynctaskMovie.execute(tosearch);
}
The Asynctask code:
class AsynctaskMovie extends AsyncTask<String, String, ArrayList<Movie>> {
JSONParser jsonParser = new JSONParser();
private static final String SEARCH_URL = "http://www.omdbapi.com/?";
#Override
protected void onPreExecute() {
super.onPreExecute();
movieArrayList = new ArrayList();
Log.i(getActivity().getCallingPackage(), "onPreExecute");
}
#Override
protected ArrayList<Movie> doInBackground(String... args) {
Log.i(getActivity().getCallingPackage(),"doInBackground");
HashMap<String, String> params = new HashMap<>();
params.put("s", args[0]);
params.put("r", "json");
JSONObject json = jsonParser.makeHttpRequest(SEARCH_URL, "GET", params);
Log.i(getActivity().getCallingPackage(), json.toString());
if (json != null) {
try {
if (json.getString("Response").equals("False")) {
return movieArrayList;
}
} catch (JSONException e) {
}
try {
JSONArray jsonArray = json.getJSONArray("Search");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
String movieid = jsonObject.getString(App.getInstance().IMDBimdbID);
if (!movieid.equals("null")) {
Movie movie = new Movie(movieid);
movieArrayList.add(movie);
}
}
jsonArray = new JSONArray();
for (Movie movie : movieArrayList) {
params = new HashMap<>();
params.put("i", movie.getMovieid());
params.put("plot", "short");
params.put("r", "json");
JSONObject jsongetfullinfo = jsonParser.makeHttpRequest(SEARCH_URL, "GET", params);
if (jsongetfullinfo != null) {
jsonArray.put(jsongetfullinfo);
Log.i("", jsongetfullinfo.toString());
}
}
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jObject = jsonArray.getJSONObject(i);
movieArrayList.get(i).updateFromIMDB(jObject);
}
for (Movie movie : movieArrayList) {
movie.setMovieposter(LoadFromUrl(movie.getPosterURL()));
}
return movieArrayList;
} catch (JSONException e) {
e.printStackTrace();
}
}
return movieArrayList;
}
#Override
protected void onPostExecute(ArrayList<Movie> movieArrayList) {
Log.i("ronen", "list size: " + movieArrayList.size());
if (movieArrayList.size() > 0) {
listView.setAdapter(new MovieAdapter(getActivity(), movieArrayList));
listView.setVisibility(View.VISIBLE);
} else {
Toast.makeText(getActivity().getApplicationContext(), "No found", Toast.LENGTH_SHORT).show();
}
}
private Bitmap LoadFromUrl(String theurl) {
URL url = null;
Bitmap bmp = null;
try {
url = new URL(theurl);
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
}
return bmp;
}
}
I have no idea what could solve this problem.
Following the answers I read here it seems that the code should work, but not so.
Can't see anything suspicious.
I'd recommend running a very simple AsyncTask on a very simple app, make sure it works (if not, maybe it something to do with the phone, so try on an emulator to be sure)
Then change it step by step to resemble your code, and you'll see where the bug is.
G'Luck!
I am trying to return multiple rows from my database. I have two coordinates that I want to retrieve that are stored in my database, namely Longitude and Latitude. As my asynctask currently only can return a row. How should I change my code so it is able to return multiple rows from the database?
Thanks for the help in advance.
Below are my codes:
php codes
$user=$_POST["username"];
$query = "SELECT longitude,latitude FROM friends INNER JOIN coordinates ON friends.username = coordinates.username WHERE friends.friend_of='$user'";
$sql=mysqli_query($conn, $query);
if (!$sql) {
echo 'Could not run query: ' . mysql_error();
exit;
}
while($row = mysqli_fetch_array($sql)>0){
$response["longitude"] = $row[0];
$response["latitude"] = $row[1];
die(json_encode($response));
}
Asynctask class.
class Findfriends extends AsyncTask<String, String, JSONObject> {
protected JSONObject doInBackground(String... args) {
// TODO Auto-generated method stub
// here Check for success tag
try {
HashMap<String, String> params = new HashMap<>();
params.put("username", args[0]);
JSONObject json = jsonParser.makeHttpRequest(
GET_FRIENDS, "POST", params);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONObject json) {
if (json != null) {
Toast.makeText(Borrower_AP.this, json.toString(),
Toast.LENGTH_LONG).show();
try {
Longitude = json.getDouble("longitude");
Latitude = json.getDouble("latitude");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
I think you have to mistakes here, the first one is that your PHP code is Just returning one row, instead you have to use something like this:
$user=$_POST["username"];
$query = "SELECT longitude,latitude FROM friends INNER JOIN coordinates ON friends.username = coordinates.username WHERE friends.friend_of='$user'";
$sql=mysqli_query($conn, $query);
if (!$sql) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$rows = array();
while($r = mysqli_fetch_assoc($sql)) {
$rows[] = $r;
}
print json_encode($rows);
On the other hand in your Android code, and if you are using Google Maps Api, you can return an ArrayList, something like this:
class Findfriends extends AsyncTask<String, String, ArrayList<LatLong> {
protected ArrayList<LatLong> doInBackground(String... args) {
// TODO Auto-generated method stub
// here Check for success tag
ArrayList<LatLong> geoPos=new ArrayList<LatLong>();
try {
HashMap<String, String> params = new HashMap<>();
params.put("username", args[0]);
JSONObject json = jsonParser.makeHttpRequest(
GET_FRIENDS, "POST", params);
if (json != null) {
Log.d("JSON result", json.toString());
//Complete here the code in which you iterate over the json and add each point to your ArrayList<LatLong>
}
} catch (Exception e) {
e.printStackTrace();
}
return geoPos;
}
}
Kindly change the php script like this,
$query = "SELECT longitude,latitude FROM friends INNER JOIN coordinates ON friends.username = coordinates.username WHERE friends.friend_of='$user'";
$sql=mysqli_query($conn, $query);
if(mysqli_num_rows($sql)>0)
{
while($row = mysqli_fetch_array($sql)
{
$latlongArray =array();
$latlongArray ["longitude"] = $row[0];
$latlongArray ["latitude"] = $row[1];
array_push($response["DATA"],$latlongArray)
}
$response["success"] = "1";
echo json_encode($response);
}
else
{
$response["success"] = "0";
echo json_encode($response);
}
And in android code, in Post execute paste this code, in logcat you will see the lat / longs from the database.
JSONArray ja = json.getJSONArray("DATA");
for (int r = 0; r < ja.length(); r++) {
JSONObject obj = ja.getJSONObject(r);
Log.i("Lat / Long",obj.getString("latitude")+" , "+obj.getString("longitude"));
}
Try this it may help you.. And it is working code.
Thank you,
Create your own handler like this:
//import android.os.Handler; this import is required.
public class MyHandler extends Handler{
public void handleMessage(Message msg) {
super.handleMessage(msg);
List<YourObject> objs=(List<YourObject>)msg.obj;
}
}
In your activity create async object as follows:
MyDataFetcher mdf=new MyDataFetcher(new MyHandler());
Write your Async like this:
class MyDataFetcher extends AsyncTask<String, String, JSONObject> {
private Handler handler
public MyDataFetcher(Handler handler){
this.handler=handler;
}
//here is code you need to write in onPost
protected void onPostExecute(JSONObject json) {
if (json != null) {
Toast.makeText(Borrower_AP.this, json.toString(),
Toast.LENGTH_LONG).show();
try {
List<YourObject> objs=new ArrayList<>();
// populate your info from json into objs
//------your code here for above logic
//Now create new Message
Message msg=new Message();
msg.obj=objs;
handler.handleMessage(msg);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
i am developing an android app which i have to integrate with backend(developed in java and spring). Which will be the best way to integrate either WebServices or through http(JSON)..?
Thanks in advance.
To get a JSON Response in Android/Java you need to do this:
Create a custom API Connector class
Declare a method that will return a JSON Array
Create a AsyncTask class (optional)
Decode JSONArray
1.
public class CustomAPIConnector {
public final String URL = "http://10.0.2.2/your-project-url/"; // 10.0.2.2 goes to computer localhost if you put localhost, it will go to the devices localhost which should not exist
2.
public JSONArray getUserInfo(String username, String password) {
HttpEntity httpEntity = null;
// Add your POST variables to receive on your backend
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username",username));
nameValuePairs.add(new BasicNameValuePair("password",password));
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL + "login.php"); // have split up URL and page so you can redirect to different links easier if the URL changes
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
httpEntity = httpResponse.getEntity();
} catch (IOException e) {
e.printStackTrace();
}
JSONArray jsonArray = null;
if(httpEntity != null) {
try {
String entityResponse = EntityUtils.toString(httpEntity);
jsonArray = new JSONArray(entityResponse);
} catch (JSONException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
}
return jsonArray;
}
}
3.
private class AvailableUser extends AsyncTask<ApiConnector,Boolean,JSONArray> {
#Override
protected JSONArray doInBackground(ApiConnector... params) {
return params[0].availableUsername(etusername.getText().toString());
}
#Override
protected void onPostExecute(JSONArray jsonArray) {
checkAvailableUsername(jsonArray);
}
}
private class AvailableEmail extends AsyncTask<ApiConnector,Boolean,JSONArray> {
#Override
protected JSONArray doInBackground(ApiConnector... params) {
return params[0].availableEmail(etemail.getText().toString());
}
#Override
protected void onPostExecute(JSONArray jsonArray) {
checkAvailableEmail(jsonArray);
}
}
4.
private void checkAvailableEmail(JSONArray jsonArray) {
String s = "";
if(jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = null;
try {
json = new JSONObject();
json = jsonArray.getJSONObject(i);
if(!json.getString("count").isEmpty()) {
if(json.getString("count").equalsIgnoreCase("0")) {
status.setText("");
passedemail = true;
return;
} else {
status.setText("Email Taken");
passedemail = false;
return;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {
status.setText("Failed - checkAvailableEmail");
}
}
Please note that this is actual code I have in one of my apps that registersa user, the getUserInfo gets all information from the user, and the Available email asynctask class is separate from the getUserInfo, it is the registering part, that checks if the email is available.
From here on, you can copy the code and change what you need to.
JSON as name says java script object notation would help you to exploit OOPS , POST/GET and js at backend .
I use JSON , its easy to code , parse and handle
I'm developing an application that connects to a PHP and get data from database.
My problem is when I get data by jParser.makeHttpRequest with internet connection and close my internet and do that again jParser.makeHttpRequest returns the last thing that it returned. It won't give No Internet Error or sοmething like that. How can I correct this?
jParser = new JSONParser();
JSONObject json = jParser.makeHttpRequest(url_get_login_infos, "GET", _params);
int success = json.getInt(TAG_SUCCESS);
String message = json.getString(TAG_MESSAGE);
Object are destroy by garbage collector. Your object still exists when you call data for the second time.
Reset your parser with null for example before you call data and test the result. Post your some code for more answers
here some of code with Json wich works fine
protected String doInBackground(String... args) {
//affectation des valeurs pour passage à PHP
String email = getEmail();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", email));
// getting JSON Object
String url = SingletonParametres.getUrlConnexion() + "get_selectuser.php";
JSONObject json = null;
try {
json = jsonParser.makeHttpRequest(url, "GET", params);
} catch (HttpException e) {
e.printStackTrace();
}
// check for success tag
try {
String Variablepourvoir = json.getString(TAG_SUCCESS);
success = json.getInt(TAG_SUCCESS);
switch (success) {
case 1: { /* user retrouvé avec succes */
// successfully select user
setCodeRetour(1);
setMsgRetour("user existe MyApplication ok");
// sauvegarde des données User dans la classApplication
// successfully received product details
JSONArray JsonUserArray = json.getJSONArray("user"); // JSON Array
// get first user object from JSON Array
JSONObject JsonUserObject = JsonUserArray.getJSONObject(0);
// user with this email found
//save data in MyApplication
MyApplication.setIdUser(JsonUserObject.getInt("iduser"));
MyApplication.setEmail(JsonUserObject.getString("email"));
MyApplication.setPseudo(JsonUserObject.getString("pseudo"));
if ( JsonUserObject.getInt("autorisation_upload") ==1 ) {
MyApplication.setAutorisationUpload(true);
} else {
MyApplication.setAutorisationUpload(false);
}
break;
}
case 0: { /* oops ! ... un probleme est survenu */
setCodeRetour(ECHEC);
setMsgRetour("user non trouvé MyApplication echec");
break;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
try this, you have that add this condition:
if(json != null){
//excecute code
}else{
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity(), "conection error", Toast.LENGTH_SHORT).show();
}
});
}
This way of writing the Toast, is if you work in a Fragment.
in your code, make this:
String url = SingletonParametres.getUrlConnexion() + "get_selectuser.php";
JSONObject json = null;
json = jsonParser.makeHttpRequest(url, "GET", params);
if(json != null) {
try {
String Variablepourvoir = json.getString(TAG_SUCCESS);
success = json.getInt(TAG_SUCCESS);
switch (success) {
case 1: {
.....
.....
}else{
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity(), "conection error", Toast.LENGTH_SHORT).show();
}
});
}