I am trying to generate List View from JSON response but unable to do it.
Getting error at line: "list_view.setAdapter(customAdapter);" #onPostExecute
NullPointerException on above line...
Complete code:
public class Screen2 extends AppCompatActivity {
ProgressDialog pDialog;
ArrayList<Information> record_list;
ListView list_view;
CustomAdapter customAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen2);
record_list=new ArrayList<Information>();
list_view=(ListView) findViewById(R.id.list_view);
new Test().execute();
}
public class Test extends AsyncTask<String, Void, ArrayList<Information>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(Screen2.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected ArrayList<Information> doInBackground(String... params) {
if(record_list.size()>0){record_list.clear();}
String jsonStr = makeServiceCall();
//ssen = new ArrayList<Information>();
try {
//HashMap<String,String> hashMap=new HashMap<>();
JSONArray jsonArray=new JSONArray(jsonStr);
for(int i=0;i<jsonArray.length();i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String id = jsonObject.getString("id");
String name = jsonObject.getString("label");
String email = jsonObject.getString("email");
Information information = new Information(id, name, email);
System.out.println("id: " + id + "name:" + name + "email" + email);
record_list.add(information);
}
System.out.println(jsonStr);
return record_list;
//return record_list;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(ArrayList<Information> s) {
super.onPostExecute(s);
for(int i=0;i<record_list.size();i++){
System.out.println(record_list.get(i));
}
if(record_list!=null && !record_list.isEmpty()){
customAdapter=new CustomAdapter(Screen2.this,record_list);
list_view.setAdapter(customAdapter);
}
else {
Toast.makeText(Screen2.this, "Array List is Empty", Toast.LENGTH_SHORT).show();
}
//ListAdapter listAdapter1=new ArrayAdapter<String>(Screen2.this,R.layout.custom_row,record_list);
//list_view.setAdapter(listAdapter);
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
}
public String makeServiceCall(){
String response = null;
try {
URL url = new URL("http://192.168.1.127:9000/tasks2");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
System.out.println("MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
System.out.println("MalformedURLException: " + e.getMessage());
} catch (IOException e) {
System.out.println("MalformedURLException: " + e.getMessage());
} catch (Exception e) {
System.out.println("MalformedURLException: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(sb);
return sb.toString();
}
}
}
Please go through the Stack Trace for the above code...
It will be very much helpful for me if anyone resolves this issue.
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.hariprasad.healthpassportnew1.Screen2$Test.onPostExecute(Screen2.java:99)
at com.example.hariprasad.healthpassportnew1.Screen2$Test.onPostExecute(Screen2.java:51)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4960)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
at dalvik.system.NativeStart.main(Native Method)
Maybe your record_list is null
so please add
if (record_list.size > 0) {
list_view.setAdapter(customAdapter);
}
and also before adding the data in record_list make clear
put this code before String jsonStr = makeServiceCall();
if (record_list.size > 0) {
record_list.clear();
}
Related
When I run the following code It does not display data.It shows the following error message:
2019-11-16 14:40:19.149 17562-17585/com.example.jsonparsing E/MainActivity: Response from url: <html>
<head><title>301 Moved Permanently</title></head>
<body bgcolor="white">
<center><h1>301 Moved Permanently</h1></center>
<hr><center>nginx/1.10.3 (Ubuntu)</center>
</body>
</html>
2019-11-16 14:40:19.149 17562-17585/com.example.jsonparsing E/MainActivity: Json parsing error: Value jsonStr of type java.lang.String cannot be converted to JSONObject
2019-11-16 14:40:19.164 17562-17589/com.example.jsonparsing I/OpenGLRenderer: Initialized EGL, version 1.4
2019-11-16 14:40:19.172 17562-17589/com.example.jsonparsing W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
MainActivity:
public class MainActivity extends AppCompatActivity {
private ArrayAdapter adapter;
public static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.recyclerview);
adapter = new ArrayAdapter(getApplicationContext());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
new getContacts().execute();
}
class getContacts extends AsyncTask<Void, Void, List<HashMap<String, String>>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(getApplicationContext(), "JSON Data is" +
" downloading", Toast.LENGTH_LONG).show();
}
#Override
protected List<HashMap<String, String>> doInBackground(Void... Void) {
HttpHandler sh = new HttpHandler();
String url = "http://api.androidhive.info/contacts/";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObject = new JSONObject("jsonStr");
List<HashMap<String, String>> contactList = new ArrayList<>();
JSONArray contacts = jsonObject.getJSONArray("contacts");
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");
JSONObject phone = c.getJSONObject("phone");
String mobile = phone.getString("mobile");
String home = phone.getString("home");
String office = phone.getString("office");
HashMap<String, String> contact = new HashMap<>();
contact.put("id", id);
contact.put("name", name);
contact.put("email", email);
contact.put("mobile", mobile);
contactList.add(contact);
}
return contactList;
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Json parsing error: "
+ e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errors",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> result) {
super.onPostExecute(result);
if (result != null) {
adapter.add(result);
adapter.notifyDataSetChanged();
}
}
}
}
HttpHandler:
class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
HttpHandler() {
}
String makeServiceCall(String reqUrl){
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn =(HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
}catch (MalformedURLException e){
Log.e(TAG,"MalformException: " + e.getMessage());
}catch (ProtocolException e){
Log.e(TAG,"ProtocolException: " + e.getMessage());
}catch (IOException e){
Log.e(TAG, "IOException: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is){
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
is.close();
}catch (IOException e){
e.printStackTrace();
}finally {
try {
is.close();
}catch (IOException e){
e.printStackTrace();
}
}
return sb.toString();
}
I want to get the username from this
Json url.
I have this code but it doesn't let me get the data saying
Json parsing error
Here is the code:
HttpHandler.java
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
// URL to get contacts JSON
private static String url = "https://someLink";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String name = c.getString("username");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("username", name);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[]{"username"}, new int[]{R.id.name});
lv.setAdapter(adapter);
}
}
}
This is an example i found on google and tried to change it a bit in my needs.I've put an empty JsonArray.I also tried other examples but i can't understand what is going wrong.
**
> New question
If my url is like this?What is the difference with the other?
**
You don't have an array to parse in the output. Your URL giving you an Object. Your code should be something like this
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String name = jsonObj.getString("username");
//... now use the whereever you want
}
catch (final JSONException e) {
//... put your error log
}
Please edit your code in MainActivity to get the username from json string as follows :
if(jsonStr!=null)
{
JSONObject jsonObj = new JSONObject(jsonStr);
if(jsonObj !=null)
{
String name = jsonObj .getString("username");
}
}
i suggest you to use this one.
public class HttpGetResources extends AsyncTask<String, Void, Object> {
#SuppressLint("StaticFieldLeak")
private ProgressBar progressBar;
private static final String RAW_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSz";
private String urlString;
private String apiName;
private Class Response_Class;
private static final Gson GSON = new GsonBuilder().setDateFormat(RAW_DATE_FORMAT).create();
private Context context;
public HttpGetResources(Context context,Class Response_Class, String apiName, String urlString) {
this.Response_Class = Response_Class;
this.apiName = apiName;
this.urlString = urlString;
this.context=context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Object response) {
super.onPostExecute(response);
}
HttpURLConnection conn = null;
OutputStreamWriter out = null;
Object result = null;
BufferedReader buffer = null;
final ExecutorService executor = Executors.newCachedThreadPool(Executors.defaultThreadFactory());
static public Future<Object> future;
#SuppressWarnings("unchecked")
#Override
protected Object doInBackground(final String... params) {
// JsonObject res=null;
future = executor.submit(new Callable<Object>() {
#Override
public Object call() throws IOException {
try {
URL url = new URL(urlString + apiName);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setConnectTimeout(3000);
conn.setReadTimeout(15000);
conn.setDoInput(true);
conn.setDoOutput(true);
out = new OutputStreamWriter(conn.getOutputStream());
out.write(params[0]);
out.flush();
out.close(); out=null;
buffer = new BufferedReader(new InputStreamReader(conn.getInputStream()));
// res= GSON.fromJson(buffer, JsonObject.class);
// result = new Gson().fromJson(res.toString(), Response_Class);
result = GSON.fromJson(buffer, Response_Class);
buffer.close(); buffer=null;
// result = new Gson().fromJson(res.toString(), Response_Class);
} catch (Exception e) {
//
} finally {
if (buffer!=null) {
try {
buffer.close();
} catch (Exception e) { //
}
}
if (out != null) {
try {
out.close();
} catch (Exception e) { //
}
}
if (conn != null) {
conn.disconnect();
}
}
return result;
}
});
try {
result = future.get(10, TimeUnit.SECONDS);
} catch (Exception ignored) {
}
return result;
}
}
--and call method--
public synchronized Object HttpGetRes(final Object REQUEST_CLASS, final Class RESPONSE_CLASS, final String
API_NAME, final String URL) {
if(isNetworkAvailable()) {
response = null;
try {
Log.e(API_NAME, "url: " + URL);
Log.e(REQUEST_CLASS.getClass().getSimpleName(), new Gson().toJson(REQUEST_CLASS));
HttpGetResources resource = new HttpGetResources(BaseContext,RESPONSE_CLASS, API_NAME,
URL);
response = resource.execute(new Gson().toJson(REQUEST_CLASS)).get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
if (response != null) {
String x = new Gson().toJson(response);
Log.e(RESPONSE_CLASS.getSimpleName(), x);
return response;
} else {
}
}
return null;
}
Try to use GSON library in the future, it will auto convert the JSON object to a java object automatically for you. This will be useful to avoid parsing complex JSON objects or JSON arrays. https://github.com/google/gson
So I've been following a tutorial that shows how to connect android to MySQL db. I've done everything, but it didn't work. The PHP file works when i enter it's location in chrome -> it shows me the array in JSON format. However, in android it's not working maybe because I am hosting the file on a local server. Any help?
Thanks.
Android:
package com.example.mohammadel_ghali.icare;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
public class login extends AppCompatActivity {
String JSON_STRING ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
public void getJSON(View view){
new BackgroundTask().execute();
}
private class BackgroundTask extends AsyncTask<Void, Void, String> {
String JSON_URL;
#Override
protected void onPreExecute() {
JSON_URL ="10.0.2.2/ApplicationDemoNewNew/admin/android/json_get_login.php";
}
#Override
protected String doInBackground(Void... voids) {
try {
StringBuilder JSON_DATA = new StringBuilder();
URL url = new URL(JSON_URL);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream in = httpURLConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
while ((JSON_STRING = reader.readLine())!=null) {
JSON_DATA.append(JSON_STRING).append("\n");
}
return JSON_DATA.toString().trim();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
TextView json = (TextView) findViewById(R.id.tv_result);
json.setText(result);
}
}
}
PHP:
<?php
$mysql_host='localhost';
$mysql_user='root';
$mysql_password='root123';
$con = #mysqli_connect($mysql_host,$mysql_user,$mysql_password);
if(!$con){
die('Failed to connect to the database');//if not successful
}else{
//echo "Successfully connected to MySQL!";//if successful
if(#mysqli_select_db($con, 'application_database')){//selecting the database
//echo '<br>'."Connected to the specified database!";
}else{
die('<br>'."Could not connect to the specified database!");
}
}
$sql = "select * from users;";
$result = mysqli_query($con,$sql);
$response = array();
while($row = mysqli_fetch_array($result)){
array_push($response, array("id"=>$row[0],"username"=>$row[1],"password"=>$row[2],"first_name"=>$row[3],"last_name"=>$row[4]));
}
echo json_encode(array("server_response"=>$response));
mysqli_close($con);
?>
This is my entire class that takes in a JSON file......
Mine goes through a json provided by NFL and I grab the teams and scores
private class GetWeekScores extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(getApplication(),"Json Data is downloading",Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler httpHandler = new HttpHandler();
// Making a request to url and getting response
for (int i = 0; i <list.size(); i++) {
String url = NFL_LIVEUPDATE_URL + list.get(i) + "/" + list.get(i) + "_gtd.json";
String jsonStr = httpHandler.makeServiceCall(url);
Log.e(TAG, "Response from url: " + url);
if (jsonStr != null) {
try {
JSONObject id = new JSONObject(jsonStr);
JSONObject home = new JSONObject(jsonStr);
JSONObject away = new JSONObject(jsonStr);
// Getting JSON Array node
final JSONObject getid = id.getJSONObject(list.get(i));
JSONObject homeScore = getid.getJSONObject("home");
JSONObject homeScore2 = homeScore.getJSONObject("score");
homeTeamABBR = homeScore.getString("abbr");
getHomeScore = homeScore2.getString("T");
JSONObject awayScore = getid.getJSONObject("away");
JSONObject awayScore2 = awayScore.getJSONObject("score");
awayTeamABBR = awayScore.getString("abbr");
getAwayScore = awayScore2.getString("T");
HashMap<String, String> homeaway = new HashMap<>();
homeaway.put("matchup", awayTeamABBR + "vs" + homeTeamABBR);
homeaway.put("homeScore", homeTeamABBR + "->" + getHomeScore + " points ");
homeaway.put("awayScore", awayTeamABBR + "->" + getAwayScore + " points ");
if (Integer.parseInt(getHomeScore) > Integer.parseInt(getAwayScore)) {
homeaway.put("winner", homeTeamABBR);
} else {
homeaway.put("winner", awayTeamABBR);
}
gameIDList.add(homeaway);
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
MethodContants.showLog(TAG, "JSON File does not exist from NFL", true);
// runOnUiThread(new Runnable() {
// #Override
// public void run() {
// Toast.makeText(getApplicationContext(),
// "Couldn't get json from server. Check LogCat for possible errors!",
// Toast.LENGTH_LONG).show();
// }
// });
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
MethodContants.showLog(TAG, "Number of games being parsed through: " + list.size(), false);
for (int i = 0; i < gameIDList.size(); i++){
System.out.println(gameIDList.get(i).get("matchup") + " -> " + gameIDList.get(i).get("homeScore") + "-> " + gameIDList.get(i).get("awayScore") + ". " + gameIDList.get(i).get("winner") + " WON!");
}
}
}
I am not sure what else your PHP file does, but if you just need info from JSON, then create a JSON file....no need to create a PHP file.
I forgot to add the HttpHandler class.
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
I want my application throws timeout after 10 seconds in AsyncTask.So what should i do ? If i am not using this so my application is crash.
And sorry for my bad English.
this is my AsyncTask
LoginTask
public class LoginTask extends AsyncTask<Void, Integer, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progress.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... params) {
/* JSONParser jParser = new JSONParser();
// JSONArray data = null;
String jsonstr = jParser.makeServiceCall(URL, JSONParser.POST);*/
BufferingH call = new BufferingH();
jsonstr = call.makeBufferCall(URL);
System.out.println("Json url view string " + jsonstr);
return null;
}
#SuppressLint("ShowToast")
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (jsonstr != null) {
try {
JSONObject jobj = new JSONObject(jsonstr);
URLmessage = jobj.getString("message").toString();
JSONArray jarray = jobj.getJSONArray("Data");
for (int i = 0; i < jarray.length(); i++) {
JSONObject jobjj = jarray.getJSONObject(i);
Username = jobjj.getString("r_name");
Password = jobjj.getString("r_password");
FirstName=jobjj.getString("first_name");
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "Invalid username password", Toast.LENGTH_SHORT).show();
Log.e("Login Screen", "Couldn't get any data from the url");
}
try {
if (URLmessage.matches("Invalid Login")) {
Toast.makeText(getApplicationContext(), "Invalid Login.....",
Toast.LENGTH_SHORT).show();
// Intent intent = new Intent(Login.this, Register.class);
// startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Login Successful...",
Toast.LENGTH_SHORT).show();
Password = et_password.getText().toString();
Username = et_username.getText().toString();
Intent k = new Intent(getBaseContext().getApplicationContext(),
MainActivity.class);
k.putExtra("regId", regId);
startActivity(k);
finish();
SettingsFragment.setDefaults("Username", Username, getApplicationContext());
SettingsFragment.setDefaults("Password", Password, getApplicationContext());
SettingsFragment.setDefaults("FirstName", Login.FirstName, getApplicationContext());
Toast.makeText(getApplicationContext(), "FirstName = "+FirstName, Toast.LENGTH_SHORT).show();
// gcmregister_from_sharedpref
gcmafterregistration();
overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);
}
} catch (Exception e) {
e.printStackTrace();
}
progress.setVisibility(View.INVISIBLE);
}
}
And this is my logcat so you can batter understand.
I have put one dummy code change your code by referring this.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (commonUtils.isNetworkAvailable(mContext)) {
NewHistoryAsync task = new NewHistoryAsync(getContext(), listDataHeader, listDataChild);
task.execute(CommonUtils._History + "ID=" + userUhid);
} else {
Toast.makeText(mContext, "No Network Available!!",
Toast.LENGTH_LONG).show();
}
private class NewHistoryAsync extends AsyncTask<String, String, String> {
ProgressDialog progressDialog;
Context mContext;
List listDataHeader;
HashMap listDataChild;
public NewHistoryAsync(Context context, List listDataHeaderList, HashMap listDataChildMap) {
mContext = context;
listDataHeader = listDataHeaderList;
listDataChild = listDataChildMap;
this.listDataHeader = new ArrayList<String>();
this.listDataChild = new HashMap<String, List<String>>();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(getActivity());
progressDialog = ProgressDialog.show(mContext, Html.fromHtml(
"<b>Heading<b>"), Html.fromHtml("<medium>Downloading Details..</medium>"), true);
// progressDialog.setTitle("Downloading Details");
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
String resResult = NewHistoryService(params[0]);
JSONObject jsonResponse;
try {
//JSONObject jsonObject = new JSONObject(resResult);
JSONArray jsonArray = new JSONArray(resResult);
// Log.i("doinb---> ", resResult);
/* ArrayList<ClaimsHistoryNewSearchModel> listDataHeader=new ArrayList<ClaimsHistoryNewSearchModel>();*/
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
List<String> historyResult = new ArrayList<String>();
historyResult.add((jsonObject.get("AdmissionDate").toString()));
historyResult.add((jsonObject.get("DischargeDate").toString()));
//AdmissionDate= exact name to ur json response from server
listDataHeader.add(KeyString);
listDataChild.put(KeyString, historyResult);
}
} catch (Exception e) {
e.printStackTrace();
}
return resResult;
}
#Override
protected void onProgressUpdate(String... values) {
Toast.makeText(mContext, values[0], Toast.LENGTH_SHORT).show();
}
#Override
protected void onPostExecute(String result) {
if (progressDialog != null && progressDialog.isShowing() == true) {
progressDialog.dismiss();
if (result.equals("[]")) {
Toast.makeText(mContext, "No Details found!!",
Toast.LENGTH_LONG).show();
} else
// Log.i("Result:", result);
// Log.i("listDataHeader:", listDataHeader.toString());
// Log.i("listDataChild:", listDataChild.toString());
listAdapter = new ClaimHistoryNewAdapter(getActivity(), listDataHeader, listDataChild);
if (listDataHeader != null && listDataHeader.size() > 0 && listDataChild != null && listDataHeader.size() > 0) {
expListView.setAdapter(listAdapter);
} else {
// setting list adapter
tClaimHistory.setVisibility(View.VISIBLE);
}
}
}
public String NewHistoryService(String serviceUrl) {
StringBuffer response = new StringBuffer();
URL url = null;
HttpURLConnection conn = null;
try {
url = new URL(serviceUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(30000);
conn.setDoOutput(false);
conn.setUseCaches(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
int status = conn.getResponseCode();
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
// Get Response
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
}
rd.close();
} catch (Exception e) {
e.printStackTrace();
//ErrorLogger.writeLog(claimNo, "Error Msg : "+e.getMessage()+"..."+ErrorLogger.StackTraceToString(e), "sendSyncService Failed");
//response.append("Error");
}
Log.v("Response:", response.toString());
return response.toString();
}
}
}
Use this JsonParser class
Hope it will help you
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class JSONParser {
public JSONParser() {
}
public String makeServiceCall(String serviceUrl) {
Boolean registered = false;
StringBuffer response = new StringBuffer();
URL url = null;
HttpURLConnection conn = null;
try {
url = new URL(serviceUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(30000);
conn.setDoOutput(false);
conn.setUseCaches(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
int status = conn.getResponseCode();
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
registered = true;
// Get Response
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
}
rd.close();
} catch (Exception e) {
e.printStackTrace();
/* ErrorLogger.writeLog(claimNo, "Error Msg : "+e.getMessage()+"..."+ErrorLogger.StackTraceToString(e), "sendSyncService Failed");
response.append("Error");*/
}
Log.v("Response:", response.toString());
return response.toString();
}
}
setConnectionTimeout(Your Time);
I am trying to read phone contacts and send that list to my server, but getting FileNotFound error in some phones but programme is working properly in some phones. following is my class -
public class UpdateNetwork extends Activity {
private String server, server_response;
private String updatenetwork = "/update-network.php";
private String data_to_send;
public JSONArray jacontacts;
public JSONObject jcontacts;
public ArrayList<String> contacts;
private ProgressDialog pd;
private Long user_id;
private MainActivity main;
JSONObject jo = null;
Button update;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.updatenetwork);
server = getString(R.string.server_add_new);
contacts = new ArrayList<String>();
main = new MainActivity();
update = (Button) findViewById(R.id.update);
update.setVisibility(View.INVISIBLE);
user_id = main.getDefaultsint("user_id", UpdateNetwork.this);
Updatenetwork un = new Updatenetwork(true);
un.execute();
update.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
URL url = null;
try {
url = new URL(server + updatenetwork);
data_to_send = "contacts=" + jcontacts + "&";
data_to_send += "user_id=" + user_id;
Updatenetwork un = new Updatenetwork(url, data_to_send);
un.execute();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public class Updatenetwork extends AsyncTask<String, Integer, JSONObject> {
private URL url;
Boolean un_send = false;
String data_to_send;
public Updatenetwork(Boolean b) {
this.un_send = b;
}
public Updatenetwork(URL url, String data_to_send2) {
this.url = url;
this.data_to_send = data_to_send2;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
if (un_send) {
update.setVisibility(View.VISIBLE);
} else {
finish();
}
pd.dismiss();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = ProgressDialog.show(UpdateNetwork.this, "Please wait...", "Sending...");
}
#Override
protected JSONObject doInBackground(String... params) {
Log.e("value of un_send", "********"+un_send+jcontacts);
if(un_send){
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
// String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
/* System.out.println("name : " + name );
*/
// get <span id="IL_AD4" class="IL_AD">the phone number</span>
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String phone = pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contacts.add(phone);
jacontacts = new JSONArray();
/* System.out.println("phone" + phone);*/
}
for(int i=0; i<contacts.size(); i++){
jacontacts.put(contacts.get(i));
}
jcontacts = new JSONObject();
try{
jcontacts.put("contacts", jacontacts);
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/* Log.e("value inside", "json obj"+jcontacts);*/
pCur.close();
jo = jcontacts;
}
}
}
} else {
BufferedReader reader=null;
try
{
Log.e("inside try block ", "get text 11111111" + data_to_send);
URLConnection conn = url.openConnection();
Log.e("inside try block ", "get text 2222222" + data_to_send);
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data_to_send);
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + "\n");
Log.e("inside ", "while loop");
}
server_response = sb.toString();
Log.e("server_response ", "server_response" +server_response);
}
catch(FileNotFoundException(String detailMessage))
{
Log.e("MyTag ", "Failure to get json data in --1--", ex);
ex.printStackTrace();
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {
Log.e("MyTag", "Failure to get json data in ", ex);
}
}
try {
jo = new JSONObject(server_response);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return jo;
}
}
}
following is what i got in errorlog
12-18 16:44:21.922: E/MyTag(32005): Failure to get json data in --1--
12-18 16:44:21.922: E/MyTag(32005): java.io.FileNotFoundException: http:// server address/update-network.php
12-18 16:44:21.922: E/MyTag(32005): at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:194)