Android HttpUrlConnection simple Website connection - android

I want to check if a local website from my apache-server is up and reachable.
If read through countless threads about HttpUrlconnection and came up with the following code. Manifest Internet Persmission is set. The website is currently running and I can access it via my smartphones webbrowser. I´ve also read about Input and Outputstreams, do I need them for my task?
public class MainActivity extends AppCompatActivity {
boolean value;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
state(value);
}
public boolean state(boolean value){
try {
URL url = new URL("http://192.168.178.59:8090/");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("HEAD");
httpURLConnection.setConnectTimeout(3000);
httpURLConnection.setReadTimeout(3000);
value = true;
Toast.makeText(MainActivity.this,"true",Toast.LENGTH_SHORT).show();
return value;
} catch (MalformedURLException e) {
e.printStackTrace();
value = false;
Toast.makeText(MainActivity.this,"false",Toast.LENGTH_SHORT).show();
return value;
} catch (IOException e) {
e.printStackTrace();
value = false;
Toast.makeText(MainActivity.this,"false",Toast.LENGTH_SHORT).show();
return value;
}
}
}
EDIT: Solution from Exception
import java.net.HttpURLConnection;
import android.os.AsyncTask;
public class MainActivity extends AppCompatActivity {
boolean value;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new HttpTask().execute(value);
}
private class HttpTask extends AsyncTask<Boolean, Void, Boolean>
{
#Override
protected Boolean doInBackground(Boolean... params) {
// TODO Auto-generated method stub
boolean value=params[0];
try {
URL url = new URL("http://192.168.178.59:8090/");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("HEAD");
httpURLConnection.setConnectTimeout(3000);
httpURLConnection.setReadTimeout(3000);
httpURLConnection.connect();
value = true;
//Toast.makeText(MainActivity.this,"true",Toast.LENGTH_SHORT).show();
return value;
} catch (MalformedURLException e) {
e.printStackTrace();
value = false;
//Toast.makeText(MainActivity.this,"false",Toast.LENGTH_SHORT).show();
return value;
} catch (IOException e) {
e.printStackTrace();
value = false;
//Toast.makeText(MainActivity.this,"false",Toast.LENGTH_SHORT).show();
return value;
}
}
#Override
protected void onPostExecute(Boolean result) {
if(result){
Toast.makeText(MainActivity.this,"true",Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(MainActivity.this,"false",Toast.LENGTH_SHORT).show();
}
}
}
}
EDIT: Service Solution
#Override
protected void onPostExecute(Boolean result) {
if(result){
Toast.makeText(NotifiyService.this,"true",Toast.LENGTH_SHORT).show();
//Notification in Status Bar
NotificationCompat.Builder builder = new NotificationCompat.Builder(NotifiyService.this);
builder.setSmallIcon(R.drawable.dummy);
Intent intent = new Intent(NotifiyService.this, Main22Activity.class);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(NotifiyService.this,0,intent,0);
builder.setContentIntent(pendingIntent);
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.dummy));
builder.setContentTitle(getResources().getString(R.string.newNotify));
builder.setContentText(getResources().getString(R.string.newNotify2));
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(1,builder.build());
}
else{
Toast.makeText(NotifiyService.this,"false",Toast.LENGTH_SHORT).show();
}

Replace your code with below given code.
import java.net.HttpURLConnection;
import android.os.AsyncTask;
public class MainActivity extends AppCompatActivity {
boolean value;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new HttpTask().execute(value);
}
private class HttpTask extends AsyncTask<Boolean, Void, Boolean>
{
#Override
protected Boolean doInBackground(Boolean... params) {
// TODO Auto-generated method stub
boolean value=params[0];
try {
URL url = new URL("http://192.168.178.59:8090/");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("HEAD");
httpURLConnection.setConnectTimeout(3000);
httpURLConnection.setReadTimeout(3000);
httpURLConnection.connect();
value = true;
//Toast.makeText(MainActivity.this,"true",Toast.LENGTH_SHORT).show();
return value;
} catch (MalformedURLException e) {
e.printStackTrace();
value = false;
//Toast.makeText(MainActivity.this,"false",Toast.LENGTH_SHORT).show();
return value;
} catch (IOException e) {
e.printStackTrace();
value = false;
//Toast.makeText(MainActivity.this,"false",Toast.LENGTH_SHORT).show();
return value;
}
}
#Override
protected void onPostExecute(Boolean result) {
if(result){
Toast.makeText(MainActivity.this,"true",Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(MainActivity.this,"false",Toast.LENGTH_SHORT).show();
}
}
}
}
EDIT:
To launch new activity on notification click, add these lines after Intent intent = new Intent(NotifiyService.this, Main22Activity.class);:
intent .setAction(Intent.ACTION_MAIN);
intent .addCategory(Intent.CATEGORY_LAUNCHER);
intent .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

Simply run this code:-
public boolean state(boolean value){
URL url;
String response = "";
try {
url = new URL("http://192.168.178.59:8090/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
//writer.write(getPostDataString(postDataParams));
writer.write(value);
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
System.out.println(response);
}
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
}

Related

In AsyncTask InputStream get android.os.NetworkOnMainThreadException

I'm getting a crash in an Android device which shows an exception about android.os.NetworkOnMainThreadException in AsyncTask. Why do I get this exception? The exception is on line 60 in onPreExecute.
I send context with WeakReference. Please explain the advantage of using WeakReference here.
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
RecyclerViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.rview);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
MyTask task = new MyTask(this);
task.execute();
}
static class MyTask extends AsyncTask {
BufferedReader reader;
private WeakReference < MainActivity > contextRef;
MyTask(MainActivity mainActivity) {
contextRef = new WeakReference < >(mainActivity);
}
#Override
protected void onPreExecute() {
try {
URL url = new URL("https://api.myjson.com/bins/1fi1zm");
URLConnection connection = url.openConnection();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
} catch(MalformedURLException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
}
#Override
protected Object doInBackground(Object[] objects) {
return null;
}
#Override
protected void onPostExecute(Object o) {
MainActivity context = contextRef.get();
if (context != null) {
Gson gson = new Gson();
List < Contact > list;
try {
list = Arrays.asList(gson.fromJson(reader.readLine(), Contact[].class));
context.adapter = new RecyclerViewAdapter(list);
context.recyclerView.setAdapter(context.adapter);
} catch(IOException e) {
e.printStackTrace();
}
}
}
}
}
The issue is for the code in onPreExecute(). It runs on Main Thread and you cannot do background task here. Try this
static class MyTask extends AsyncTask {
BufferedReader reader;
private WeakReference<MainActivity> contextRef;
MyTask(MainActivity mainActivity) {
contextRef = new WeakReference<>(mainActivity);
}
#Override
protected void onPreExecute() {
}
#Override
protected Object doInBackground(Object[] objects) {
try {
URL url = new URL("https://api.myjson.com/bins/1fi1zm");
URLConnection connection = url.openConnection();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Object o) {
MainActivity context = contextRef.get();
if (context != null) {
Gson gson = new Gson();
List<Contact> list;
try {
list = Arrays.asList(gson.fromJson(reader.readLine(), Contact[].class));
context.adapter = new RecyclerViewAdapter(list);
context.recyclerView.setAdapter(context.adapter);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Let me know if it solved your issue.
replace your code with this
#Override
protected void onPreExecute() {
}
#Override
protected Object doInBackground(Object[] objects) {
try {
URL url = new URL("https://api.myjson.com/bins/1fi1zm");
URLConnection connection = url.openConnection();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return reader;
}

Android - Call Thread synchronized on UI thread

I try to create synchronized threads, but I always get the following error: android.os.NetworkOnMainThreadException.
I've read more posts, but they don't work for me.
Below I write the code blocks that do not work for me:
1.
final SyncApp syncJob = new SyncApp();
Thread t = new Thread (new Runnable () {
                         #Override
                         public void run () {
                             synchronized (syncJob) {
                                 String s = syncJob.insert (newJobs, GlobalVariables.URL_LOCALHOST + "jobs");
                                 txtState.setText (s);
                             }}});
                         }
                     });
                     t.Start ();
// t.run ();
2.
myClass.runOnUiThread(new Runnable() {
public void run() {...}
})
3.
Running code in main thread from another thread
SyncApp:
public class SyncApp {
synchronized public String insert(List<Jobs> job, String... params) {
URL url = null;
HttpURLConnection conn = null;
try {
url = new URL(params[0]);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoInput(true);
conn.setDoOutput(true);
String str = new Gson().toJson(job);
byte[] outputInBytes = str.getBytes();
OutputStream os = conn.getOutputStream();
os.write( outputInBytes );
os.flush();
int responseCode=conn.getResponseCode();
String response = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
}
else {
response=conn.getResponseMessage();
}
return response;
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.disconnect();
}
return null;
}
}
I need to call a thread, wait for the answer and call another thread. Their answers I must use them in the activity
I need to call a thread, wait for the answer and call another thread.
Their answers I must use them in the activity
Example using async tasks to accomplish objective.
In this code, let A be your activity which needs to call a thread,
wait for the answer and call another thread. Customize as needed.
Since you never wait in UI threads, callbacks are used to accomplish synchronization.
Let A be your activity class:
public class A extends Activity {
// some method in activity where you launch a background thread (B)
// which then completes and invokes callback which then creates and launches
// a background thread (C) which then completes and invokes a callback.
//
// In callback C, you are on the UI thread.
protected void someMethod() {
new B(new B.CallbackB() {
public void result(Object o) {
new C(new C.CallbackC() {
public void result(Object o, Object answerFromB) {
// OK - C is now done and we are on UI thread!
// 'o' is answer from C
// 'answerFromB' also provided
}
}, o).execute(new Object());
}
).execute(new Object());
}
}
Define a class B:
public class B extends AsyncTask<Object, Void, Object> {
public static interface CallbackB {
void result(Object o);
}
private CallbackB cb;
public B (CallbackB cb) {
this.cb = cb;
}
protected Object doInBackground(Object... params) {
// do work and return an answer.
return new Object();
}
protected void onPostExecute(Object result) {
if (cb != null) {
cb.result(result);
}
}
}
Define a class C:
public class C extends AsyncTask<Object, Void, Object> {
public static interface CallbackC {
void result(Object o, Object answerFromB);
}
private CallbackC cb;
private Object answerFromB;
public C (CallbackC cb, Object answerFromB) {
this.cb = cb;
this.answerFromB = answerFromB;
}
protected Object doInBackground(Object... params) {
// do work and return an answer.
return new Object();
}
protected void onPostExecute(Object result) {
if (cb != null) {
cb.result(result, answerFromB);
}
}
}
For reference:
https://stackoverflow.com/a/9963705/2711811
My solution is:
public class Sync extends AppCompatActivity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sync_server);
dao = new DAO(this);
txtState = findViewById(R.id.txt_log);
btnSincro = findViewById(R.id.btn_sincro);
btnSincro.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countCall = 0;
callFlow();
}
});
btnHome = findViewById(R.id.btn_home);
btnHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SyncServerActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
private void callFlow() {
switch (countCall) {
case 0:
templates = toTemplate("url");
break;
case 1:
jobs = toJobs("url");
break;
case 2:
job = ... //select item
res = sendJobs(jobs, "url");
break;
default:
runOnUiThread(new Runnable() {
#Override
public void run() {
btnSincro.setEnabled(true);
txtState.append("\n\nEND");
}
});
}
}
private void nextStep() {
setText(txtState, "\nSync \n" + countCall + "/3");
countCall++;
callFlow();
}
private void setText(final TextView text, final String value) {
runOnUiThread(new Runnable() {
#Override
public void run() {
text.setText(value);
}
});
}
public List<Templates> toTemplate(final String... params) {
final List<Templates> list = new ArrayList<>();
Thread t = new Thread(new Runnable() {
#Override
public void run() {
URL url = null;
BufferedReader reader = null;
HttpURLConnection connection = null;
try {
url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
int responseCode = connection.getResponseCode();
String response = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("data");
for (int i = 0; i < parentArray.length(); i++) {
Templates item = new Gson().fromJson(parentArray.get(i).toString(), Templates.class);
list.add(item);
}
} else {
response = connection.getResponseMessage();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
nextStep(); //call next Thread
}
}
});
t.start();
return list;
}
public List<Jobs> toJobs(final String... params) {
final List<Jobs> list = new ArrayList<>();
Thread t = new Thread(new Runnable() {
#Override
public void run() {
URL url = null;
BufferedReader reader = null;
HttpURLConnection connection = null;
try {
url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
int responseCode = connection.getResponseCode();
String response = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("data");
for (int i = 0; i < parentArray.length(); i++) {
Jobs item = new Gson().fromJson(parentArray.get(i).toString(), Jobs.class);
list.add(item);
}
} else {
response = connection.getResponseMessage();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
nextStep();
}
}
});
t.start();
return list;
}
public Boolean sendJobs(final List<Jobs> job, final String... params) {
final Boolean[] result = {false};
Thread t = new Thread(new Runnable() {
#Override
public void run() {
URL url = null;
HttpURLConnection conn = null;
try {
url = new URL(params[0]);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoInput(true);
conn.setDoOutput(true);
String str = new Gson().toJson(job);
Log.d(TAG, str);
byte[] outputInBytes = str.getBytes();
OutputStream os = conn.getOutputStream();
os.write(outputInBytes);
os.flush();
int responseCode = conn.getResponseCode();
String response = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
result[0] = true;
} else {
response = conn.getResponseMessage();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.disconnect();
nextStep();
}
}
});
t.start();
return result[0];
}
}
Whenever a thread ends, it calls the nextStep() method, which starts the next trhead.

Calling AsyncTask class it does not execute doInBackgound method

when calling
new AsyncFeed(strurl).execute();
after this its able to call constructor of AsyncFeed but not able to execute doInBackground(). while debugging i found out it calls constructor and then simply returns back to the calling statement making a nullpointer exception in later code
public class HttpHandler {
public HttpHandler() {
}
URL url;
HttpURLConnection httpURLConnection = null;
InputStream inputStream;
BufferedReader bufferedReader = null;
StringBuffer stringBuffer;
String strurl;
public String getJsonString(String strurl){
new AsyncFeed(strurl).execute();
return String.valueOf(stringBuffer);
}
class AsyncFeed extends AsyncTask<String,Void,String>{
String urlStr;
public AsyncFeed(String urlStr) {
this.urlStr=urlStr;
}
#Override
protected String doInBackground(String... strings) {
try {
url = new URL(urlStr);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
inputStream = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
stringBuffer = new StringBuffer();
while ((line=bufferedReader.readLine()) != null){
stringBuffer.append(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(bufferedReader !=null)
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
httpURLConnection.disconnect();
}
return null;
}
If you think that stringBuffer is null, it's because function public String getJsonString(String strurl) returns String value of uninitialized stringBuffer before AsyncFeed is completed. You should use something like this:
public void loadJsonString(String strurl){
new AsyncFeed(strurl).execute();
//return String.valueOf(stringBuffer);
}
class AsyncFeed extends AsyncTask<Void,Void,Void>{
String urlStr;
public AsyncFeed(String urlStr) {
this.urlStr=urlStr;
}
#Override
protected String doInBackground(Void... records) {
try {
url = new URL(urlStr);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
inputStream = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
stringBuffer = new StringBuffer();
while ((line=bufferedReader.readLine()) != null){
stringBuffer.append(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(bufferedReader !=null)
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
httpURLConnection.disconnect();
}
return null;
}
#Override
protected void onPreExecute() {
//f.e. show progress dialog
}
#Override
protected void onPostExecute(Void result) {
//now you have initialized stringBuffer so do what you want with it
//hide progress dialog
//print String value of stringBuffer initialized in doInBackground
System.out.print(String.valueOf(stringBuffer));
}
)
There are more options to do that but it's hard to write exactly what you need without seeing more of your code or specify your question, so if you have some
questions to me just write comment :) or read more here Android Developers - AsyncTask
EDIT
Okay I understand, try do it like this, the idea is just pass calling object into the async task and from there in onPostExecute() will be updated data
in ClassA and continue with what you need
public class ClassA{
String url;
String jsonObjectString;
//instead of getJsonString(url) call this and after async task will finish
//it calls updateDataFromAsync() so you will have data loaded and you can continue work with it in doSomethingAfterAsync()
private void loadData(){
//pass the calling object into the async task
new HttpHandler(this).startLoadJsonString(url);
}
//this will async taks call in onPostExecute()
public void updateDataFromAsync(String s){
jsonObjectString = s;
doSomethingAfterAsync();
}
private doSomethingAfterAsync(){
}
}
public class HttpHandler {
URL url;
HttpURLConnection httpURLConnection = null;
InputStream inputStream;
BufferedReader bufferedReader = null;
StringBuffer stringBuffer;
String strurl;
ClassA classA;
public HttpHandler(ClassA classA) {
this.classA = classA;
}
public void startLoadJsonString(String strurl){
new AsyncFeed(strurl).execute();
}
private class AsyncFeed extends AsyncTask<Void,Void,Void>{
String urlStr;
public AsyncFeed(String urlStr) {
this.urlStr=urlStr;
}
#Override
protected String doInBackground(Void... records) {
try {
url = new URL(urlStr);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
inputStream = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
stringBuffer = new StringBuffer();
while ((line=bufferedReader.readLine()) != null){
stringBuffer.append(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(bufferedReader !=null)
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
httpURLConnection.disconnect();
}
return null;
}
#Override
protected void onPreExecute() {
//f.e. show progress dialog
}
#Override
protected void onPostExecute(Void result) {
//now you have initialized stringBuffer so do what you want with it
//hide progress dialog
//call updateDataFromAsync from ClassA class and continue there
classA.updateDataFromAsync(String.valueOf(stringBuffer));
}
)

read from json (string) android with Gson

its my json file
{"VisitorsList":[{"VisitorID":"09005451","VisitorName":" xxxx","VisitorPhon":"","VisitorAddr":"xxxx","GeoCode":"","AutoKey":1},{"VisitorID":"09005468","VisitorName":"xxxxxx","VisitorPhon":"09005468","VisitorAddr":"xxxx","GeoCode":"","AutoKey":2}]}
and i wanna read and show information from this file to a ListView
my VisitorsListActivity is:
public class VisitorsListActivity extends AppCompatActivity {
public ListView lstVisitors;
static VisitorsList visitorsList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.visitor_list);
try {
//********************************** COMELETE THIS SECTION *********************************************
new JsonHelper.GetJsonData(new JsonHelper.GetJsonData.AsyncResponse() {
#Override
public void processFinish(String output) {
try {
if (output == null) output = "";
if (output.equals("")) {
Toast.makeText(getApplicationContext(),
"No Visitor Founded",
Toast.LENGTH_LONG)
.show();
return;
}
//960105--------------------
else if (output.equals("401")) {
Toast.makeText(getApplicationContext(),
"Error 401",
Toast.LENGTH_LONG)
.show();
return;
}
//--------------------------------------
Log.i("LOG", "output" + output);
Gson gson = new Gson();
output = output.substring(1, output.length() - 1);
/*Toast.makeText(getApplicationContext(),
output,
Toast.LENGTH_LONG)
.show();*/
visitorsList = new VisitorsList();
visitorsList = gson.fromJson(output, VisitorsList.class);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"exception",
Toast.LENGTH_LONG)
.show();
}
}
}).execute("http://192.168.1.162:8014/api/Visitors");
//************************************ visitor list is null :| *******************************************
/*if( visitorsList == null) {
Toast.makeText(getApplicationContext(),
"data is nul",
Toast.LENGTH_LONG)
.show();
}*/
AdapterVisitor customAdapter = new AdapterVisitor(this, R.layout.visitor_list, visitorsList.VisitorsList);
customAdapter.notifyDataSetChanged();
lstVisitors.setAdapter(customAdapter);
lstVisitors.requestFocus();
final ViewGroup layoutClear = (ViewGroup) findViewById(R.id.layoutClear);
layoutClear.setVisibility(View.GONE);
} catch (Exception e) {
e.getMessage();
}
} }
and VisitorsList:
public class VisitorsList {
public VisitorsList() {}
public ArrayList<Visitors> VisitorsList;}
Visitors:
public class Visitors {
public String VisitorID;
public String VisitorName;
public String VisitorPhon;
public String VisitorAddr;
public String GeoCode;
public int AutoKey;}
and always visitor list which created by Gson is null. i dont know maybe my problem is in reading from json or maybe visitors class ...
jsonhelper :
public class JsonHelper {
public static class GetJsonData extends AsyncTask<String, Void, String> {
public interface AsyncResponse {
void processFinish(String output);
}
public AsyncResponse delegate = null;
public GetJsonData(AsyncResponse delegate) {
this.delegate = delegate;
}
#Override
protected String doInBackground(String... strUrl) {
String str = strUrl[0];
URLConnection urlConn = null;
BufferedReader bufferedReader = null;
try {
URL url = new URL(str);
urlConn = url.openConnection();
urlConn.setReadTimeout(300000);
urlConn.setConnectTimeout(5000);
bufferedReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "utf-8"), 8);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
}
String tmpJson = stringBuffer.toString().replace("\\", "");
return tmpJson;
} catch (Exception ex) {
ex.getMessage();
return null;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
#Override
protected void onPostExecute(String response) {
delegate.processFinish(response);
}
}
public static class SetJsonData extends AsyncTask<String, Void, String> {
String responseServer;
public interface AsyncResponse {
void processFinish(String output);
}
public AsyncResponse delegate = null;
public SetJsonData(AsyncResponse delegate) {
this.delegate = delegate;
}
#Override
protected String doInBackground(String... param) {
URL url;
String response = null;
try {
url = new URL(param[0]);
HttpURLConnection conn = null;
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(20000);
conn.setConnectTimeout(10000);//950718
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(param[1]);
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = (String.valueOf(responseCode));
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));//950427
while ((line = br.readLine()) != null) {
}
}
return response;
} catch (IOException e1) {
e1.getMessage();
return null;
} catch (Exception e) {
e.getMessage();
return null;
}
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
try {
super.onPostExecute(result);
delegate.processFinish(result);
} catch (Exception e) {
e.getMessage();
}
}
}}
your visitors class is missing annotations.
use this to convert it properly:
http://www.jsonschema2pojo.org/
Check this https://kylewbanks.com/blog/Tutorial-Android-Parsing-JSON-with-GSON
to read the JSON with GSON.
well at first read AsyncResponse so you are using asynchronous request is that what are doing ?
An asynchronous request doesn't block the client so it continue executing the code when the response is back it will execute what is inside the callback.
But you are calling the customAdapter.notifyDataSetChanged(); outside processFinish() you need to call it inside or call the Adapter work inside the processFinish method.
public class VisitorsList {
public VisitorsList() {}
public ArrayList VisitorsList= new ArrayList<>();}
Should be like this... Intialization is missing.
VisitorsList class :
public class VisitorsList {
#SerializedName("VisitorsList")
public List<VisitorsList> VisitorsList;
public static class VisitorsList {
#SerializedName("VisitorID")
public String VisitorID;
#SerializedName("VisitorName")
public String VisitorName;
#SerializedName("VisitorPhon")
public String VisitorPhon;
#SerializedName("VisitorAddr")
public String VisitorAddr;
#SerializedName("GeoCode")
public String GeoCode;
#SerializedName("AutoKey")
public int AutoKey;
}
}
delete this line
output = output.substring(1, output.length() - 1);
and get your result:
Gson gson = new Gson();
visitorsList=gson.fromJson(output), new TypeToken<VisitorsList>() { }.getType());
i change VisitorsListActivity same as below . and set a condition before call adapter to be sure reading information from json has been finished, this worked correctly :
new JsonHelper.GetJsonData(new JsonHelper.GetJsonData.AsyncResponse() {
#Override
public void processFinish(String output) {
try {
if (output == null) output = "";
if (output.equals("")) {
Toast.makeText(getApplicationContext(),
"No Visitor Founded",
Toast.LENGTH_LONG)
.show();
return;
}
else if (output.equals("401")) {
Toast.makeText(getApplicationContext(),
"Error 401",
Toast.LENGTH_LONG)
.show();
return;
}
Log.i("LOG", "output" + output);
Gson gson = new Gson();
output = output.substring(1, output.length() - 1);
try {
visitorsList = new VisitorsList();
visitorsList = gson.fromJson(output, VisitorsList.class);
if(visitorsList != null) {
d.cancel();
adapter = new AdapterVisitor(visitorsList.VisitorsList);
adapter.notifyDataSetChanged();
lstVisitors.setAdapter(adapter);
lstVisitors.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ******
Object o = lstVisitors.getItemAtPosition(position);
Intent i = new Intent(getApplicationContext(),DateSelectorActivity.class);
Visitors v = (Visitors) o;
i.putExtra("VisitorID", v.VisitorID);
startActivity(i);
}
});
}
}catch (Exception e) {
Log.i("LOG", getAssets().toString() + "exception" + e);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).execute(url);

sending data to server from text file using a service

I am sending data from text file to server using service code given below. It sends data line by line to server. I want the service to run in background continuously.For this I have written asyncTask. But it sends all data once and then stops.
public class BackgroundService extends Service
{
private static final String TAG = "BackgroundService";
String line=null;
Context mContext = null;
File file;RandomAccessFile in = null;
StringEntity se ;
HttpEntity entity=null;
final static int SERVICE_NAME = 1;
int WORK_TYPE;
public BackgroundService()
{
//super(TAG);
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),"in BackgroundService", Toast.LENGTH_LONG).show();
mContext = getBaseContext();
WORK_TYPE = 2;
new BackgroundTask(mContext).execute();
return super.onStartCommand(intent, flags, startId);
}
public class BackgroundTask extends AsyncTask<String, String, Void>
{
Context mContext = null;String response;
public BackgroundTask(Context context)
{
mContext = context;
}
protected void onPreExecute()
{
Toast.makeText(getApplicationContext(),"1", Toast.LENGTH_LONG).show();
}
protected Void doInBackground(final String... args)
{
switch (WORK_TYPE)
{
case 2:
File file = new File(Environment.getExternalStorageDirectory(),"/BPCLTracker/gpsdata.txt");
int i=0;
RandomAccessFile in = null;
try {
in = new RandomAccessFile(file, "rw");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
while ((line = in.readLine()) != null)
{
String input = line.toString();
response = sendDataToServer(input);
// JsonUtils.parseServerData(response, hashMapObj);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}//switch
return null;
}//doInBackground
protected void onPostExecute(final Void unused)
{
Toast.makeText(getApplicationContext(),"3", Toast.LENGTH_LONG).show();
switch (WORK_TYPE)
{
case 2:
if (!"".equalsIgnoreCase(response) && response != null)
{
//DeviceUtils.deviceRegistration(hashMapObj, mContext);
callService(1);
}
try {
if((line = in.readLine()) == null && entity!=null)
{
file.delete();
new BackgroundTask(mContext).execute();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
}
public void callService(int work)
{
WORK_TYPE = work;
new BackgroundTask(mContext).execute();
}
public String sendDataToServer(String data)
{
StringBuffer sb = new StringBuffer("");
String serverUrl = "http://67.23.166.35:80/android/insert.php" ;
try
{
URL url = new URL(serverUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(6 * 10 * 1000);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
conn.setRequestMethod("POST");
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
while ((line = rd.readLine()) != null)
{
// Process line...
sb.append(line);
}
wr.close();
rd.close();
return sb.toString();
}
catch (Exception e)
{
Log.d("Exception : ", e.getStackTrace().toString());
}
return sb.toString();
}
}
Thank you
I have Modify your code:
Check my all code this ll give you idea about send line one by one. Please do rest of logic this way. i have also remove some method.
This is not all code but it ll give you IDEA.
package com.example.getjson;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.entity.StringEntity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class backservice extends Service {
private static final String TAG = "BackgroundService";
String line = null;
Context mContext = null;
File file;
RandomAccessFile in = null;
StringEntity se;
HttpEntity entity = null;
final static int SERVICE_NAME = 1;
int WORK_TYPE;
String response;
String input = "";
public backservice() {
// super(TAG);
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "in BackgroundService",
Toast.LENGTH_LONG).show();
mContext = getBaseContext();
WORK_TYPE = 2;
// new BackgroundTask(mContext).execute();
switch (WORK_TYPE) {
case 2:
File file = new File(Environment.getExternalStorageDirectory(),
"/BPCLTracker/gpsdata.txt");
int i = 0;
RandomAccessFile in = null;
try {
in = new RandomAccessFile(file, "rw");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
while ((line = in.readLine()) != null) {
input = line.toString();
// response = sendDataToServer(input);
new BackgroundTask(mContext).execute();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
return super.onStartCommand(intent, flags, startId);
}
public class BackgroundTask extends AsyncTask<String, String, Void> {
Context mContext = null;
public BackgroundTask(Context context) {
mContext = context;
}
protected void onPreExecute() {
Toast.makeText(getApplicationContext(), "1", Toast.LENGTH_LONG)
.show();
}
protected Void doInBackground(final String... args) {
response = sendDataToServer(input);
return null;
}
protected void onPostExecute(final Void unused) {
}
}
public void callService(int work) {
WORK_TYPE = work;
new BackgroundTask(mContext).execute();
}
public String sendDataToServer(String data) {
StringBuffer sb = new StringBuffer("");
String serverUrl = "http://67.23.166.35:80/android/insert.php";
try {
URL url = new URL(serverUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(6 * 10 * 1000);
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
conn.setRequestMethod("POST");
OutputStreamWriter wr = new OutputStreamWriter(
conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line = "";
while ((line = rd.readLine()) != null) {
// Process line...
sb.append(line);
}
wr.close();
rd.close();
return sb.toString();
} catch (Exception e) {
Log.d("Exception : ", e.getStackTrace().toString());
}
return sb.toString();
}
}

Categories

Resources