I am creating a Quiz app on android studio and the questions will be called from an URL containing a JSONObject, and since these API calls happen asynchronously,
i have to make sure that my app is waiting for the server to respond with a callback, below is the parsing method i created following some internet tutorials, it would be nice if you could help me understand which changes should i apply
private void jsonParse(){
final Question[] quest =new Question[10];
String url="https://opentdb.com/api.php?amount=10";
JsonObjectRequest request =new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray ja=response.getJSONArray("results");
for(int i=0;i<3;i++){
JSONObject temp_quest=ja.getJSONObject(i);
String question =temp_quest.getString("question");
String correctanswer=temp_quest.getString("correct_answer");
String incorrectanswer_1=(String)temp_quest.getJSONArray("incorrect_answers").getString(0);
String incorrectanswer_2=(String)temp_quest.getJSONArray("incorrect_answers").getString(1);
String incorrectanswer_3=(String)temp_quest.getJSONArray("incorrect_answers").getString(2);
String[] temp=new String[3];
temp[0]=incorrectanswer_1;
temp[1]=incorrectanswer_2;
temp[2]=incorrectanswer_3;
quest[i]=new Question(question,correctanswer,temp);
mTextViewResult.append(quest[i].getQuestion()+" \n"+ quest[i].getCorrectAnswer()+"\n "+
quest[i].getAnswer(1)+"\n "+quest[i].getAnswer(2)+"\n "+
quest[i].getAnswer(3)+"\n" +quest[i].getAnswer(4)+"\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
}
}
I consider that you are not using the correct form to call a service.
You can use a async task
package principal.concrete.concrete;
import android.os.AsyncTask;
import android.util.Log;
import java.io.IOException;
import java.net.URL;
import java.net.HttpURLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Post extends AsyncTask<String, Void, String> {
private InputStreamReader inputStreamReader;
private BufferedReader bufferedReader;
#Override
protected String doInBackground(String... params){
try {
URL obj = new URL(params[0]);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", " ");
con.connect();
inputStreamReader=new InputStreamReader(con.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
return bufferedReader.readLine();
}catch(Exception e){
Log.d("Url doInBackground", e.toString());
return null;
} finally {
try {
closeConnection();
} catch(Exception e){
}
}
}
private void closeConnection() {
try {
if(bufferedReader!=null){
bufferedReader.close();
}
if(inputStreamReader!=null){
inputStreamReader.close();
}
}catch(IOException ex){
Log.d("Url disconnect", ex.toString());
}
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
}
}
You can use a retrofit to call a service
link the implementation
https://programacionymas.com/blog/consumir-una-api-usando-retrofit
I have a code to call service
asyn task
Related
So there is a background Service which creates Runnable objects as soon as GPS Location is changed. Runnable contains HTTPConnection to make POST and twice send broadcast message via sendBroadcast().
So the problem I am facing if there is no chance to send data by this scheme something happened and app craches.
Any clue to refactor code or may be change approach to TaskAsync and cancel pending TaskAsync when new TaskAsync is ready?
Any clue?
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.text.format.DateFormat;
import android.util.Log;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
public class gps_service2 extends Service {
private static final String TAG = "GPS SERVICE";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 10000;
private static final float LOCATION_DISTANCE = 10f;
Context context;
private class LocationListener implements android.location.LocationListener
{
Location mLastLocation;
public LocationListener(String provider)
{
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location)
{
Log.e(TAG, "onLocationChanged: " + location);
try
{
ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences(context, "App_Settings", 0);
AppSettings appSettings = complexPreferences.getObject("App_Settings", AppSettings.class);
if (appSettings != null) {
LocationItem locationItem = new LocationItem();
locationItem.DeviceID = appSettings.getDeviceID();
locationItem.Latitude = Double.toString(location.getLatitude());
locationItem.Longitude = Double.toString(location.getLongitude());
Date d = new Date();
CharSequence timeOfRequest = DateFormat.format("yyyy-MM-dd HH:mm:ss", d.getTime()); // YYYY-MM-DD HH:mm:ss
locationItem.TimeOfRequest = timeOfRequest.toString();
locationItem.SerialNumber = appSettings.getSerialNumber();
Gson gson = new Gson();
String requestObject = gson.toJson(locationItem);
String url = appSettings.getIpAddress() + "/api/staff/savedata";
makeRequest(url, requestObject, dLocation);
}
}
catch (Exception ex)
{
}
}
#Override
public void onProviderDisabled(String provider)
{
Log.e(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider)
{
Log.e(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
Log.e(TAG, "onStatusChanged: " + provider);
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onCreate()
{
context = this;
Log.e(TAG, "onCreate");
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
}
#Override
public void onDestroy()
{
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
public void makeRequest(String uri, String json, DLocation dLocation) {
HandlerThread handlerThread = new HandlerThread("URLConnection");
handlerThread.start();
Handler mainHandler = new Handler(handlerThread.getLooper());
Runnable myRunnable = createRunnable(uri, json, dLocation);
mainHandler.post(myRunnable);
}
private Runnable createRunnable(final String uri, final String data,final DLocation dLocation){
Runnable aRunnable = new Runnable(){
public void run(){
try {
//Connect
HttpURLConnection urlConnection;
urlConnection = (HttpURLConnection) ((new URL(uri).openConnection()));
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.connect();
//Write
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
try {
writer.write(data);
} catch (IOException e) {
e.printStackTrace();
Log.d(TAG,"Ошибка записи в буфер для пережачи по HTTP");
}
writer.close();
outputStream.close();
//Read
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
bufferedReader.close();
String result = sb.toString();
Log.d(TAG, result);
Intent iResult = new Intent("location_update");
DLocation dLocation = new DLocation();
iResult.putExtra("result", dLocation);
sendBroadcast(iResult);
}catch( Exception err){
err.printStackTrace();
Log.d(TAG, "HTTP " + err.getMessage());
}
}
};
return aRunnable;
}
}
Runnable is just an interface, when you create a thread using Runnable interface basically it will run under the the thread where it created, in here runnable associate with UI thread, as per google documentation Network calls must be in a worker thread not in UI thread.
Then Why it runs on emulator
android had DVM(dalvik virtual machine),it works like JVM but instead of .class file DVM uses .dex extension, so may the device had older or newer version of DVM.
Fix
Use android's AsyncTask for network calls. android(DVM) had limited resources compare to JVM, when it comes to thread, so better use AsyncTask
check this answer too
AsyncTask code for passing JSON to server, and get responds as callback
public class WebService extends AsyncTask<String,String,String> {
private static final String TAG="SyncToServerTAG";
private String urlString;
private JSONObject jsonObject=null;
private int screenId=1;
public WebService(String url) {
this.urlString=url;
}
public WebService(Context context, String url, JSONObject jsonObject) {
this.urlString = url;
this.jsonObject = jsonObject;
}
#Override
protected String doInBackground(String... strings) {
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setChunkedStreamingMode(0);
urlConnection.setConnectTimeout(5000);
urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
if(jsonObject!=null) {
OutputStream os = urlConnection.getOutputStream();
os.write(jsonObject.toString().getBytes("UTF-8"));
}
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(
(urlConnection.getInputStream())));
String output="";
while (true) {
String line=br.readLine();
Log.d(TAG,line+" ");
if(line!=null)
output+=line;
else
break;
}
in.close();
urlConnection.disconnect();
JSONObject j;
if(output.equals(""))
publishProgress("Server give null");
else {
j=new JSONObject(output);
return output;
}
return output;
} catch (MalformedURLException e) {
e.printStackTrace();
publishProgress(e.toString());
} catch (IOException e) {
e.printStackTrace();
publishProgress(e.toString());
} catch (JSONException e) {
e.printStackTrace();
publishProgress(e.toString());
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
fireError(values[0]);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(s!=null) {
try {
JSONObject jsonObject=new JSONObject(s);
fireComplete(0, jsonObject);
} catch (JSONException e) {
e.printStackTrace();
fireError("Non acceptable responds from server ["+urlString+"]");
}
}
}
public interface OnWebCompleteListener{
void onComplete(JSONObject result, int dataSource);
void onError(String error);
}
private OnWebCompleteListener onWebCompleteListener;
private void fireComplete(int sourse,JSONObject cache){
if(onWebCompleteListener!=null)
onWebCompleteListener.onComplete(cache,sourse);
}
private void fireError(String message){
if(onWebCompleteListener!=null)
onWebCompleteListener.onError(message);
}
public void start(OnWebCompleteListener onWebCompleteListener){
if(onWebCompleteListener==null)
throw new RuntimeException("You must provide non-null value as start listener");
this.onWebCompleteListener=onWebCompleteListener;
execute((String)null);
}
}
Usage
WebService webService=new WebService(context,"url",jsonObject);
webService.start(new WebService.OnWebCompleteListener() {
#Override
public void onComplete(JSONObject result, int dataSource) {
}
#Override
public void onError(String error) {
}
});
Your code is very vulnerable. I think that you crash because your makeRequest method exits before you Runnable had the chance to complete the task.
You closed the resource as soon as you send them, freeing system resources.
There for the second time you call broadcast, the resources are not there anymore causing the crash....
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
So I am trying to fetch JSON string from a website which looks like this
[{"name":"Painting"},{"name":"Painting or varnishing doors"},{"name":"Painting or varnishing frames"},{"name":"Varnishing floors"},{"name":"Picking old wallpaper"},{"name":"Painting the facade"},{"name":"professional athlete"}]
I just want to fetch the first JSONObject with the string "Painting".
Here's my MainActivity.java code
package mobiletest.pixelapp.com.mobiletest;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import model.Cup;
public class MainActivity extends AppCompatActivity {
private TextView textView;
private String myString;
private String anotherString;
private String myVar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.textView);
Cup myCup = new Cup();
String newString = myCup.myMethod();
try {
JSONArray jsonArray = new JSONArray(newString);
JSONObject jsonObject = jsonArray.getJSONObject(0);
Log.v("Key",jsonObject.getString("name"));
textView.setText(jsonObject.getString("name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Here's my java class file cup.java
package model;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
/**
* Created by pruthvi on 12/2/2015.
*/
public class Cup {
public String myMethod()
{
String output = getUrlContents("http://xyz.co/tests/android-query.php");
return output;
}
private static String getUrlContents(String theUrl)
{
StringBuilder content = new StringBuilder();
// many of these calls can throw exceptions, so i've just
// wrapped them all in one try/catch statement.
try
{
// create a url object
URL url = new URL(theUrl);
// create a urlconnection object
URLConnection urlConnection = url.openConnection();
// wrap the urlconnection in a bufferedreader
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
// read from the urlconnection via the bufferedreader
while ((line = bufferedReader.readLine()) != null)
{
content.append(line + "\n");
}
bufferedReader.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return content.toString();
}
}
Now the problem, when I run this code as java I am easily able to print painting from the JSONObject, but when I try to run it as an android view by setting the text for my TextView, I am getting some strange system.err
12-02 14:06:26.809 19250-19250/mobiletest.pixelapp.com.mobiletest D/libc: [NET] getaddrinfo hn 10, servname NULL, ai_family 0+
12-02 14:06:26.809 19250-19250/mobiletest.pixelapp.com.mobiletest W/System.err: at java.net.InetAddress.lookupHostByName(InetAddress.java:393)
12-02 14:06:26.809 19250-19250/mobiletest.pixelapp.com.mobiletest W/System.err: at java.net.InetAddress.getAllByNameImpl(InetAddress.java:244)
12-02 14:06:26.809 19250-19250/mobiletest.pixelapp.com.mobiletest W/System.err: at java.net.InetAddress.getAllByName(InetAddress.java:219)
I am new to java and android, and as of now I just want to get data from my remote server files and database.
Thanks in advance
look at this example it will give you an idea
AsyncTask<Void, Void, Void> asyncLoad = new AsyncTask<Void, Void, Void>()
{
#Override
protected Void doInBackground(Void... params)
{
URL url = new URL("http://www.omdbapi.com/?i=&t="
+ TITLE);
String URL2="http://www.omdbapi.com/?i=&t=saw";
Log.d("URL content", url.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
Log.d("URL content", "register URL");
urlConnection.connect();
Log.d("URL connection", "establish connection");
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
}
};
asyncLoad.execute();
Do like that in onCrate Method
try {
JSONArray jsonArray = new JSONArray(newString);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.getString("name")
textView.setText(name));}
} catch (JSONException e) {
e.printStackTrace();
}
It will set name to textView.
Happy to Help and Happy Coding
You can't do network task in UI Thread.
So
String newString = myCup.myMethod();
not properly working.
Main Reason of those errors are related with thread context.
If you want to do network task with android, use async task or other network library (personally I recommend retrofit).
try
{
JSONArray jsonArray = new JSONArray(newString);
if(jarray.length()>0){
String name = jarray.getJSONObject(0).getString("name");
displayName(name); //new method
}catch(Exception e){
}
Define the method displayName(String) like this outside onCreate()
public void displayName(final String name){
runOnUiThread(new Runnable() {
#Override
public void run() {
textView.setText(jsonObject.getString("name"));
}
});
}
Im kinda new in android development, Im trying to do a login process for app, i have successfully complete the process with http post method on a php script on my local host, however to make my login process nicer i decided use progressdialog to show when the authentication process runs but the progress keeps looping. Below is my code:
LoginActivity.java - login button:
opt = new HttpRequest();
btnLogin = (Button)findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
v.setEnabled(false);
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
private boolean authResult = false;
#Override
protected void onPreExecute() {
pd = new ProgressDialog(context);
pd.setTitle("Processing...");
pd.setMessage("Please wait.");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
#Override
protected Void doInBackground(Void... arg0) {
try {
//Do something...
if(opt.loginAuth(txtUsername.getText().toString(), txtPassword.getText().toString())){
Log.i(Data.tagInfo,"Redirecting to mainpage");
opt.showToast(LoginActivity.this,"Login Successful");
startActivity(new Intent("com.example.MainActivity"));
}
else{
opt.showToast(LoginActivity.this,"Login Fail");
Log.i(Data.tagError,"Login Fail");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (pd!=null) {
pd.dismiss();
btnLogin.setEnabled(true);
}
}
};
task.execute((Void[])null);
}
});
HttpRequest.java:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutionException;
import org.json.JSONArray;
import android.os.AsyncTask;
import android.util.Log;
public class HttpRequest extends Operations {
public boolean loginAuth(String user , String pass){
//Log.i("Info",user+"|"+pass);
String folder = "mobileapp",
script = "/loginAuth_m-script.php",
fullpath = folder+script,
parameter = "username="+user+"&password="+pass,
result = "";
try {
JSONArray jArray = convertJSON(new SendRequest().execute(fullpath,parameter).get());
result = getSpecificJSONdata(jArray,"result");
Log.i(Data.tagInfo,"Login result:"+result);
if(result.equals(Data.success)){
Log.i(Data.tagInfo,"loginAuth() return true");
return true;
}
else{
Log.i(Data.tagInfo,"loginAuth() return false");
return false;
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.i(Data.tagError,"Error:"+e.toString());
return false;
}
}
private class SendRequest extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... arg) {
// TODO Auto-generated method stub
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
String response = null;
try
{
url = new URL("http://"+Data.host+"/"+arg[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(arg[1]);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
// Response from server after login process will be stored in response variable.
response = sb.toString();
// You can perform UI operations here
Log.i("Info","Server Response:"+response);
isr.close();
reader.close();
return response;
}
catch(IOException e)
{
Log.i("InfoError",e.toString());
return "";
// Error
}
}
}
}
Thanks alot in advance^^
I am trying to get a response from a service (the response comes in json).
I made my checks if the device is connected and now I need to make the http request to the service. I found out on other questions that I have to use a background thread but I am not sure I got a working sample.
So I need to find out how I can make a connection to a given uri and read the response.
My service needs to get a content header application/json in orderto return a json, so before the request I need to set this header as well.
Thank you in advance
UPDATE
package com.example.restfulapp;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.provider.Settings;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.ExecutionException;
public class MainActivity extends Activity {
private int code = 0;
private String value = "";
private ProgressDialog mDialog;
private Context mContext;
private String mUrl ="http://192.168.1.13/myservice/upfields/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (!isOnline())
{
displayNetworkOption ("MyApp", "Application needs network connectivity. Connect now?");
}
try {
JSONObject s = getJSON(mUrl);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
public class Get extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... arg) {
String linha = "";
String retorno = "";
mDialog = ProgressDialog.show(mContext, "Please wait", "Loading...", true);
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(mUrl);
try {
HttpResponse response = client.execute(get);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Ok
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
while ((linha = rd.readLine()) != null) {
retorno += linha;
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return retorno;
}
#Override
protected void onPostExecute(String result) {
mDialog.dismiss();
}
}
public JSONObject getJSON(String url) throws InterruptedException, ExecutionException {
setUrl(url);
Get g = new Get();
return createJSONObj(g.get());
}
private void displayNetworkOption(String title, String message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder
.setTitle(title)
.setMessage(message)
.setPositiveButton("Wifi", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
}
})
.setNeutralButton("Data", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
startActivity(new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
return;
}
})
.show();
}
private boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
}
This throws errors:
Gradle: cannot find symbol method setUrl(java.lang.String)
Gradle: cannot find symbol method createJSONObj(java.lang.String)
After derogatory responses from EvZ who think that he was born knowing everything, I ended up with a subclass MyTask that I call like this inside the onCreate of my Activity.
new MyTask().execute(wserviceURL);
private class MyTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
URL myurl = null;
try {
myurl = new URL(urls[0]);
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection connection = null;
try {
connection = myurl.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
connection.setConnectTimeout(R.string.TIMEOUT_CONNECTION);
connection.setReadTimeout(R.string.TIMEOUT_CONNECTION);
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestProperty("Content-Type", getString(R.string.JSON_CONTENT_TYPE));
int responseCode = -1;
try {
responseCode = httpConnection.getResponseCode();
} catch (SocketTimeoutException ste) {
ste.printStackTrace();
}
catch (Exception e1) {
e1.printStackTrace();
}
if (responseCode == HttpURLConnection.HTTP_OK) {
StringBuilder answer = new StringBuilder(100000);
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
String inputLine;
try {
while ((inputLine = in.readLine()) != null) {
answer.append(inputLine);
answer.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
httpConnection.disconnect();
return answer.toString();
}
else
{
//connection is not OK
httpConnection.disconnect();
return null;
}
}
#Override
protected void onPostExecute(String result) {
String userid = null;
String username = null;
String nickname = null;
if (result!=null)
{
try {
//do read the JSON here
} catch (JSONException e) {
e.printStackTrace();
}
}
//stop loader dialog
mDialog.dismiss();
}
}
lory105's answer guided me to somewhere near the answer, thanx.
here is an example of how to process the HTTP response and convert to JSONObject:
/**
* convert the HttpResponse into a JSONArray
* #return JSONObject
* #param response
* #throws IOException
* #throws IllegalStateException
* #throws UnsupportedEncodingException
* #throws Throwable
*/
public static JSONObject processHttpResponse(HttpResponse response) throws UnsupportedEncodingException, IllegalStateException, IOException {
JSONObject top = null;
StringBuilder builder = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
String decoded = new String(builder.toString().getBytes(), "UTF-8");
Log.d(TAG, "decoded http response: " + decoded);
JSONTokener tokener = new JSONTokener(Uri.decode(builder.toString()));
top = new JSONObject(tokener);
} catch (JSONException t) {
Log.w(TAG, "<processHttpResponse> caught: " + t + ", handling as string...");
} catch (IOException e) {
Log.e(TAG, "caught: " + e, e);
} catch (Throwable t) {
Log.e(TAG, "caught: " + t, t);
}
return top;
}
From Android 3+, the http connections must be done within a separate thread. Android offers a Class named AsyncTask that help you do it.
Here you can find a good example of an AsyncTask that performs an http request and receives a JSON response.
Remember that in the doInBackgroud(..) method you CAN'T modify the UI such as to launch a Toast, to change activity or others. You have to use the onPreExecute() or onPostExecute() methods to do this.
ADD
For the mDialog and mContext variables, add the code below, and when you create the JSONTask write new JSONTask(YOUR_ACTIVITY)
public abstract class JSONTask extends AsyncTask<String, Void, String> {
private Context context = null;
ProgressDialog mDialog = new ProgressDialog();
public JSONTask(Context _context){ context=_context; }
..