App crashes when connection is lost while using HttpUrlConnection - java

i'm making a class that get json data from an external url, it is working fine if there is a connection. also shows an error if there isn't.
the problem is if the connection lost while the class is getting data the app crashes.
here is my code:
//I always check connection before calling the class
class GetPost extends AsyncTask<String, String, String>
{
Context c;
String res;
public GetPost(Context c){
this.c=c;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
Earn.statu.setText("Loading post...");
}
#Override
protected String doInBackground(String[] p1)
{
try{
URL u = new URL(p1[0]);
HttpURLConnection con = (HttpURLConnection) u.openConnection();
InputStream is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
res = br.readLine();
}
catch (MalformedURLException e){}
catch (IOException e){}
return res;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
try{
JSONObject jo = new JSONObject(res);
Earn.getVideoData(c,
jo.getString("pid"),
jo.getInt("duration"),
jo.getInt("id")
);
}catch(JSONException a){}
}
so guys is there any solution to prevent the app from crashing?

Set timeout on request by example:
try {
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setRequestMethod("HEAD");
con.setConnectTimeout(5000); //set timeout to 5 seconds
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
} catch (java.net.SocketTimeoutException e) {
return false;
} catch (java.io.IOException e) {
return false;
}

Related

how to get the text that was set dynamically to a TextView?

In my MainActivity.java i have set some text to a TextView, how do I get the text that I had set to the TextView
My Textview -
<TextView
android:id="#+id/show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="visible" />
ASyncTask -
public class fetchdata extends AsyncTask<Void, Void, Void> {
private String data = "";
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("https://blablabla.com/hello.json");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
data = bufferedReader.readLine();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
MainActivity.show.setText(this.data);
}
}
MainActivity -
private static TextView show;
...... show is static
show = findViewById(R.id.show);
String data = show.getText().toString();
but data is empty instead of me getting "this is the text I want to get"
Considering the fact that the following two lines are together,
show = findViewById(R.id.show);
String data = show.getText().toString();
I'm gonna guess that they are in the onCreate, thereby resulting in empty data.
You'll need to wait for the AsyncTask to complete and TextView to have it's value set in onPostExecute before you try to get it in the UI thread. (You could use a callback)
class fetchdata extends AsyncTask<Void, Void, String> {
private String data = "";
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL("https://blablabla.com/hello.json");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
return data = bufferedReader.readLine();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String aVoid) {
super.onPostExecute(aVoid);
show.setText(aVoid);
}
}

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

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

Call Async task from start of activity in android

I have a Async task like this in my app:
private class getUserSummary extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(DashboardActivity.this);
pDialog.setMessage("Getting sales summary...");
//pDialog.setTitle("Getting sales summary...");
pDialog.setIndeterminate(true);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... strings) {
String JsonResponse = null;
String JsonDATA = "email=my email address";
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
try {
ServiceUrl smf = new ServiceUrl();
URL url = new URL(smf.getUserSummaryUrl());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
// is output buffer writter
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//set headers and method
Writer writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"));
writer.write(JsonDATA);
// json data
writer.close();
int responseCode = urlConnection.getResponseCode();
if (responseCode == 400) {
InputStream inputResponse = urlConnection.getErrorStream();
reader = new BufferedReader(new InputStreamReader(inputResponse));
StringBuffer errorBuffer = new StringBuffer();
String errorLine;
while ((errorLine = reader.readLine()) != null) {
errorBuffer.append(errorLine + "\n");
}
Log.i("Error text", errorBuffer.toString());
return new JSONObject(errorBuffer.toString());
}
//Log.i("Response code", String.valueOf(inputStream));
InputStream inputStream = urlConnection.getInputStream();
//input stream
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String inputLine;
while ((inputLine = reader.readLine()) != null)
buffer.append(inputLine + "\n");
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
JsonResponse = buffer.toString();
//response data
Log.i("RESPONSE", JsonResponse);
return new JSONObject(JsonResponse);
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("ERROR", "Error closing stream", e);
}
}
}
return null;
}
protected void onPostExecute(JSONObject result) {
pDialog.dismiss();
//post operation here
}
}
and calling this in onCreate() method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
ButterKnife.bind(this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
initCollapsingToolbar();
new getUserSummary().execute();
}
I am running this as soon as user login activity distroyed. that's why I need to call this on onCreate() method. But I am getting this error when the call this in onCreate() method
android.view.WindowLeaked: Activity softlogic.computers.softlogicsalesreward.DashboardActivity has leaked window com.android.internal.policy.PhoneWindow$DecorView{5329b90 V.E...... R......D 0,0-1002,348} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:603)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:326)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:109)
at android.app.Dialog.show(Dialog.java:505)
at softlogic.computers.softlogicsalesreward.DashboardActivity$getUserSummary.onPreExecute(DashboardActivity.java:88)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:604)
at android.os.AsyncTask.execute(AsyncTask.java:551)
at softlogic.computers.softlogicsalesreward.DashboardActivity.onResume(DashboardActivity.java:65)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1287)
at android.app.Activity.performResume(Activity.java:7015)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4210)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4323)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3426)
at android.app.ActivityThread.access$1100(ActivityThread.java:229)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7325)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
is there any other event where I can call this? or what I am doing wrong?
Your asyncTask must be like this.After see your code it may possible that You may forgot some method of AsyncTask.Compare with this example to better understand.
This is complete example of asyncTask:
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
private String resp;
ProgressDialog progressDialog;
#Override
protected String doInBackground(String... params) {
publishProgress("Sleeping..."); // Calls onProgressUpdate()
try {
int time = Integer.parseInt(params[0])*1000;
Thread.sleep(time);
resp = "Slept for " + params[0] + " seconds";
} catch (InterruptedException e) {
e.printStackTrace();
resp = e.getMessage();
} catch (Exception e) {
e.printStackTrace();
resp = e.getMessage();
}
return resp;
}
#Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
progressDialog.dismiss();
finalResult.setText(result);
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(MainActivity.this,
"ProgressDialog",
"Wait for "+time.getText().toString()+ " seconds");
}
#Override
protected void onProgressUpdate(String... text) {
finalResult.setText(text[0]);
}
}
call like this:
new AsyncTaskRunner (this).execute();
you can use thread policy for this. It's work great.
Just add two line below setcontent.
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.build();
StrictMode.setThreadPolicy(policy);
You Forget to call pDialog.dismiss();
in onPostExecute method of Async task

Fetching Data from JSON using AsyncTask

I have created a fragment which if it is activated it will show MySQL data but it takes time to fetch the data and show it on a custom ListView.
I tried to implement AsyncTask so that while fetching the data you can do something else on the fragment while waiting but am having this error.
"FATAL EXCEPTION: main java.lang.NullPointerException"
Here is the code
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_markets,container,false);
//lvMarkets.setAdapter(new CustomAdapter(getActivity().getApplicationContext(),Symbols,Prices,Balances));
DBHelper db = new DBHelper(getActivity().getApplicationContext());
final ListView lvMarkets = (ListView)getActivity().findViewById(R.id.lvMarkets);
final String c_androidid = Settings.Secure.getString(getActivity().getContentResolver(), Settings.Secure.ANDROID_ID);
final Cursor rs = db.getID(c_androidid);
rs.moveToFirst();
final String c_login = rs.getString(rs.getColumnIndex(DBHelper.c_login));
AsyncTaskRunner taskRunner = new AsyncTaskRunner();
taskRunner.execute(c_login);
lvMarkets.setAdapter(jAdapter);
return rootView;
}
private class AsyncTaskRunner extends AsyncTask<String,String,String>
{
#Override
protected String doInBackground(String... params)
{
final String fin_login=params[0];
StringRequest stringRequest = new StringRequest(Request.Method.POST,url, new Response.Listener<String>() {
#Override
public void onResponse(String response)
{
Log.d(debug,response);
try
{
jsonArray =new JSONArray(response);
jAdapter= new JsonAdapter(getActivity(),jsonArray,login);
}
catch (JSONException e)
{
Log.d(debug,e.toString());
}
}
}, new Response.ErrorListener()
{
public void onErrorResponse(VolleyError error)
{
Log.d(debug,error.toString());
}
}){
#Override
protected Map<String,String>getParams()
{
Map<String,String> params=new HashMap<String,String>();
params.put("c_login",fin_login);
return params;
}
};
RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
queue.add(stringRequest);
return fin_login;
}
}
Hope someone could point out what went wrong with my code and someone could also point out on how to fetch data on online much more faster.
Thanks...
Try this:
private void parsingValues() {
URL obj = null;
HttpURLConnection con = null;
String USER_AGENT = "Mozilla/5.0";
try {
//parameter to post
String POST_PARAMS = "deviceos=" + deveiceOs + "&devicetype=" + deviceType +"&deviceid=" ;
obj = new URL("Your URI");
con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//getResponse
String subsResponse = response.toString();
final JSONObject responsesubs = new JSONObject(subsResponse);
//Here your parsing process
}
}
});
} else {
System.out.println("POST request not worked");
}
} catch (Exception e) {
e.printStackTrace();
}
}
// Call this method to your doinbackground of Asynhronous Task(parsingValues())

How to stop HttpURLConnection.getInputStream()?

Below is my code:
private HttpURLConnection connection;
private InputStream is;
public void upload() {
try {
URL url = new URL(URLPath);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.connect();
is = connection.getInputStream();
} catch (Exception e) {
e.printStackTrace();
}
}
public void stopupload() {
connection = null;
is = null;
}
When I upload file, the line is = connection.getInputStream(); will spend a lot of time to get reply. So I want to implement a stop function as stopupload(). But if I call stopupload() while the code is handling at line is = connection.getInputStream();, it still needs to wait for its reply.
I want to stop waiting at once while implement stopupload(). How can I do it?
But if I call stopupload() while the code is handling at line is =
connection.getInputStream();, it still needs to wait for its reply.
Starting from HoneyComb, all network operations are not allowed to be executed over main thread. To avoid getting NetworkOnMainThreadException, you may use Thread or AsyncTask.
I want to stop waiting at once while implement stopupload(). How can I
do it?
Below code gives the user to stop uploading after 2 seconds, but you can modify the sleep times (should be less than 5 seconds) accordingly.
upload:
public void upload() {
try {
URL url = new URL(URLPath);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.connect();
// run uploading activity within a Thread
Thread t = new Thread() {
public void run() {
is = connection.getInputStream();
if (is == null) {
throw new RuntimeException("stream is null");
}
// sleep 2 seconds before "stop uploading" button appears
mHandler.postDelayed(new Runnable() {
public void run() {
mBtnStop.setVisibility(View.VISIBLE);
}
}, 2000);
}
};
t.start();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
if (connection != null) {
connection.disconnect();
}
}
}
onCreate:
#Override
public void onCreate(Bundle savedInstanceState) {
// more codes...
Handler mHandler = new Handler();
mBtnStop = (Button) findViewById(R.id.btn_stop);
mBtnStop.setBackgroundResource(R.drawable.stop_upload);
mBtnStop.setOnClickListener(mHandlerStop);
mBtnStop.setVisibility(View.INVISIBLE);
View.OnClickListener mHandlerStop = new View.OnClickListener() {
#Override
public void onClick(View v) {
stopUpload(); // called when "stop upload" button is clicked
}
};
// more codes...
}
private HttpURLConnection connection;
private InputStream is;
public void upload() {
try {
URL url = new URL(URLPath);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.connect();
Thread t = new Thread() {
public void run() {
is = connection.getInputStream();
}
};
t.start()
} catch (Exception e) {
e.printStackTrace();
}catch (InterruptedException e) {
stopupload(connection ,is, t);
}
}
public void stopupload(HttpURLConnection connection ,InputStream is,Thread t) {
if(connection != null ){
try {
t.interupt();
running = false;
connection=null;
is=null;
} catch (Exception e) {
}
}
}
Wrap the code that uses HttpURLConnection inside a Future, as described here.

Categories