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)
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
JSONParser.class
package com.example.diptiagravat.myapplication;
public class JSONParser {
public String getJSON(String url, int timeout) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
return null;
}
public String sendHTTPData(String urlpath, String id) {
HttpURLConnection connection = null;
try {
URL url=new URL(urlpath);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
OutputStreamWriter streamWriter = new OutputStreamWriter(connection.getOutputStream());
streamWriter.write(id);
streamWriter.flush();
StringBuilder stringBuilder = new StringBuilder();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK){
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(streamReader);
String response = null;
while ((response = bufferedReader.readLine()) != null) {
stringBuilder.append(response + "\n");
}
bufferedReader.close();
Log.d("test", stringBuilder.toString());
return stringBuilder.toString();
} else {
Log.e("test", connection.getResponseMessage());
return null;
}
} catch (Exception exception){
Log.e("test", exception.toString());
return null;
} finally {
if (connection != null){
connection.disconnect();
}
}
}
}
MainActivity.java
package com.example.diptiagravat.myapplication;
public class MainActivity extends AppCompatActivity {
private TextView txtid, txtcname;
Spinner spcnt, spstate;
public ArrayList<String> clist;
ArrayAdapter<String> cad;
public ArrayList<String> slist;
ArrayAdapter<String> sad;
public String strcnt;
private static String url = "http://urmiinfotech.com/demo/ifirst/app_api/get_country_list.php";
private static String stateUrl = "http://urmiinfotech.com/demo/ifirst/app_api/get_state_list.php";
private static final String TAG_USER = "country";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "country_name";
private ArrayList<Country> clistModels;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
CountryAsyncTask countryAsyncTask= new CountryAsyncTask();
countryAsyncTask.execute();
}
private void initViews() {
txtid = (TextView) findViewById(R.id.tvid);
txtcname = (TextView) findViewById(R.id.tvcname);
spcnt = (Spinner) findViewById(R.id.spcnt);
spstate = (Spinner) findViewById(R.id.spstate);
clist = new ArrayList<String>();
slist = new ArrayList<String>();
}
public class CountryAsyncTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = null;
try {
json = new JSONObject(jParser.getJSON(url, 5000));
} catch (JSONException e) {
e.printStackTrace();
}
return json.toString();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.i("Result Ravi", result);
try {
JSONObject obj = new JSONObject(result);
JSONArray cntArray = obj.getJSONArray("country");
if (cntArray.length() > 0) {
for (int i = 0; i < cntArray.length(); i++) {
final JSONObject temp = cntArray.getJSONObject(i);
// txtid.setText(temp.getString("id"));
// txtcname.setText(temp.getString("country_name"));
Country country = new Gson().fromJson(temp.toString(), Country.class);
clist = new ArrayList<String>();
clistModels = new ArrayList<Country>();
clistModels.add(new Country(temp.optString("id"), temp.optString("country_name"), "", null));
clist.add(temp.getString("country_name"));
cad = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, clist);
spcnt.setAdapter(cad);
spcnt.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
strcnt = clistModels.get(position).getId();
//strcnt = parent.getItemAtPosition(position).toString();
Log.i("id", strcnt);
new StatesAsyncTask().execute();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// txtid.setText(temp.getString(country.getId()));
// txtcname.setText(temp.getString(country.getCountryName()));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class StatesAsyncTask extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = null;
try {
json = new JSONObject(jParser.sendHTTPData(stateUrl, strcnt));
} catch (JSONException e) {
e.printStackTrace();
}
return json.toString();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject obj = new JSONObject(s);
JSONArray stArray = obj.getJSONArray("statelist");
if (stArray.length() > 0) {
for (int i = 0; i < stArray.length(); i++) {
final JSONObject temp = stArray.getJSONObject(i);
// txtid.setText(temp.getString("id"));
// txtcname.setText(temp.getString("country_name"));
Statelist stlist = new Gson().fromJson(temp.toString(), Statelist.class);
slist = new ArrayList<String>();
// clistModels = new ArrayList<Country>();
//clistModels.add(new Country(temp.optString("id"), temp.optString("country_name"), "", null));
slist.add(temp.getString("state_name"));
sad = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, slist);
spstate.setAdapter(sad);
spstate.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// strcnt = clistModels.get(position).getId();
//strcnt = parent.getItemAtPosition(position).toString();
// Log.i("id", strcnt);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// txtid.setText(temp.getString(country.getId()));
// txtcname.setText(temp.getString(country.getCountryName()));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
My response is null?
HttpURLConnection is deprecated in Android Lollipop, so please try to use DefaultHttpClient instead. Also, check your logs, this is at your onPostExecute():
Log.i("Result Ravi", result);
For DefaultHttpClient check this post.
Another way is to try Retrofit
I want to optimize my code to reduce the run time of my application. Currently it takes 18secs to load and show the welcome screen.
I am using AsyncTask to put all of my operation(JSON parsing, Database operations). Is there any else method that I can use to shave off at least 4secs from my application.
I can show the code if you want. Please let me know.
Thanking you
I've shared the code here please go through it.
public class MainActivity extends Activity {
/** THE FOLLOWING STRINGS WILL BE DISPLAYED IN LOGCAT */
final String TAG = "##--MAIN ACTIVITY--##";
UserHelper userAdapter;
Context context;
String regName="";
int duration = Toast.LENGTH_LONG;
String regNameSplit[];
JSONObject second_jsonObj = null;
JSONObject jsonObj = null;
JSONObject jsonobj = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
userAdapter = new UserHelper(this);
context = getApplicationContext();
final EditText edit_password = (EditText)findViewById(R.id.password);
final EditText edit_username = (EditText)findViewById(R.id.user_name);
final EditText edit_company = (EditText)findViewById(R.id.company_string);
final Button login = (Button)findViewById(R.id.login_button);
login.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
/*THE IF STATEMENT CHECKS IF THE FIELDS ARE EMPTY OR NOT*/
if (edit_username.getText().toString().equals("") || edit_username.getText().toString() == null ||
edit_password.getText().toString().equals("") || edit_password.getText().toString() == null||
edit_company.getText().toString().equals("") ||edit_company.getText().toString() == null ){
Log.i(TAG,"User has left some fields empty");
Toast.makeText(getApplicationContext(), "Enter all details", duration).show();
} else{
jsonobj = new JSONObject();
try{
//THE TRY STATEMENT CREATES A NEW JSON OBJECT TO BE PARSED IN HANDLEJSON METHOD//
JSONObject subJson = new JSONObject();
subJson.put("username", edit_username.getText().toString()/*"da"*/);
subJson.put("password", edit_password.getText().toString()/*"exicom"*/);
subJson.put("company", edit_company.getText().toString()/*"utb17"*/);
jsonobj.put("user", subJson);
Log.i(TAG,""+jsonobj);
}
catch(JSONException e) {
Log.i("","#####-----error at catch jsonexception-----#####");
}
//JSON OBJECT IS PARSED OVER HERE //
new synchronizeData(URL, jsonobj).execute();
}
}
});
}
class synchronizeData extends AsyncTask<Void, String, Void>{
private String name1;
private String company1;
private String password1;
private String regnaMe1;
private String reg1name1;
ProgressDialog PD ;
public synchronizeData(String name, String password, String company,
String regnaMe, String reg1name) {
// TODO Auto-generated constructor stub
this.name1 = name;
this.company1 = company;
this.password1 = password;
this.regnaMe1 = regnaMe;
this.reg1name1 = reg1name ;
}
public synchronizeData(String uRL, JSONObject jsonobj) {
// TODO Auto-generated constructor stub
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
Log.v(TAG,"Start of doInBackground");
try{
//Log.v(TAG,"The url is ********* "+URL);
//Log.v(TAG, "Json object request is "+jsonobj.toString());
DefaultHttpClient httpClientInstance = GetHttpClient.getHttpClientInstance();
HttpPost httpPostRequest = new HttpPost(URL);
Log.v(TAG,"The url is ********* "+URL);
StringEntity se;
se = new StringEntity(jsonobj.toString());
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");
long t = System.currentTimeMillis();
HttpResponse response = (HttpResponse) httpClientInstance.execute(httpPostRequest);
//Log.i(TAG, "HTTPRESPONSE RECIEVED in " +(System.currentTimeMillis()-t) + "ms");
String resultString = convertStreamToString(response.getEntity().getContent());
//Log.v(TAG ,/* "The response is "resultString);
jsonObj = new JSONObject(resultString);
JSONObject sessionJson = jsonObj.getJSONObject("session");
String sessionId = sessionJson.getString("sessionid");
String name = sessionJson.getString("name");
//Log.v(TAG,"The session ID is "+sessionId);
//Log.v(TAG,"The name is "+name);
regName = name+"-"+sessionId+"-"+URL;
} catch (JSONException e){
try{
Log.i(TAG,"JSON EXCEPTION FIRST");
JSONObject messageJson = jsonObj.getJSONObject("message");
String typeJson = messageJson.getString("type");
String contentJson = messageJson.getString("content");
regName = contentJson;
e.printStackTrace();
}catch(JSONException jse){
jse.printStackTrace();
}catch(Exception ee){
ee.printStackTrace();
}
}catch(Exception ee){
ee.printStackTrace();
}
Log.v(TAG,"before the return statement "+regName.toString());
//return regName;
try{
String regNameSplit[] = regName.split("-");
if(regNameSplit[0].equals("Invalid username or password")){
Toast.makeText(getApplicationContext(), ""+regNameSplit[0], duration).show();
}
else{
String regnaMe = regNameSplit[0].toString();
String reg1name = regNameSplit[1].toString();
Log.v(regnaMe,reg1name);
Intent intent = new Intent(MainActivity.this, Secondactivity.class);
intent.putExtra("regName", regNameSplit[0]);
intent.putExtra("regName_sessionID", regNameSplit[1]);
intent.putExtra("regName_URL", regNameSplit[2]);
startActivity(intent);
}
userAdapter.openDatabase();
//-------------THE DATABASE CHECKS IF THE VALUE IS PRESENT OR NOT IF TRUE DOESN'T INSERT-----------//
if(db.Exists(name1) == true){
} else {
long id = db.insertIntoDatabase(name1,company1,password1,regnaMe1,reg1name1);
Log.i(TAG, "Printing value of id which will be inserted only to remove warnings "+id);
}
}
catch(SQLiteException e){
e.printStackTrace();
}
return null;
}
private java.lang.String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try{
while((line = reader.readLine()) !=null ){
sb.append(line + "\n");
}
}
catch (IOException e){
e.printStackTrace();
} finally{
try {
is.close();
} catch (IOException e){
e.printStackTrace();
}
}
return sb.toString();
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
PD = new ProgressDialog(MainActivity.this);
PD.setMessage("Please wait....");
PD.show();
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
PD.dismiss();
userAdapter.closeDatabase();
}
}
}
This is the code for the second activity:
String ht = "";
public final String TAG = "###---Secondactivity---###";
public String reg_name = "";
public String resultString = "";
// AccessTimeReportTableHelper dB;
JSONObject jsonobj = null;
Vector objVector = new Vector();
String bufferedValue = "";
String newdeletedtrsArray = "";
String newschemaArray = "";
String newtrsArray = "";
String URL_ = "";
AccessTimeReportTableHelper useradapter_TimeReportTable;
AccessMessageTable useradapterMessageTable;
AccessMessageTypeTable useradapterMessageTypeTable;
UserHelper userHelper;
AccessTimeReportMessage useradapterTimeReportMessage;
String[] split_newdeletedtrsArray;
String[] split_newschemaArray;
String[] split_newtrsArray;
String[] splitno1_split_newtrsArray;
ArrayList<GetSetMethod> bulk = new ArrayList<GetSetMethod>();
ProgressDialog PD;
#SuppressWarnings({ "rawtypes", "unused" })
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondactivity);
Log.v(TAG, "Start of second activity");
userHelper = new UserHelper(this);
useradapterMessageTable = new AccessMessageTable(this);
useradapter_TimeReportTable = new AccessTimeReportTableHelper(this);
useradapterMessageTypeTable = new AccessMessageTypeTable(this);
useradapterTimeReportMessage = new AccessTimeReportMessage(this);
if (getIntent().getStringExtra("regName") != null) {
try {
String name = getIntent().getStringExtra("regName");
String session_ID = getIntent().getStringExtra(
"regName_sessionID");
URL_ = "URL inserted here";
jsonobj = new JSONObject("custom JSON OBJECT HERE");
String ht = URL_ + "&" + jsonobj;
// Log.i("" + ht, "");
JSONObject jsonObj = null;
String resultString = "";
String deletedtrsArray = "";
String newtrsArray = "";
String newschemaArray = "";
String bufferedValue = "";
Log.v(TAG, "The url is " + URL_);
Log.v(TAG, "Json object request is " + jsonobj.toString());
new AsyncSecondActivity(jsonobj).execute();
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception en) {
en.printStackTrace();
}
}
Log.v(TAG, "Ending program execution here");
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
class AsyncSecondActivity extends AsyncTask<Void, String, Void> {
private String newcompanyid1;
private String newdate1;
private String newusername1;
private String newClientId1;
private String newprojectId1;
private String newniV1;
private String newniV2;
private String newworktypeid1;
private String newtimetypeid1;
private String newhours1;
private String newcomment1;
private String newprivatecomment1;
private String newopen1;
private String newreportid1;
String messageTypeId = "";
String messageConcat = "";
String concatCursorCompare = "";
String newcompanyid;
String date_id = "";
String compareId = "";
String newusername = "";
String newdate = "";
String newClientId = "";
String newprojectId = "";
String newniv1 = "";
String newniv2 = "";
String newworktypeid = "";
String newtimetypeid = "";
String newhours = "";
String newcomment = "";
String newprivatecomment = "";
String newopen = "";
String newreportid = "";
String dateId = "";
String messageType_System = "";
String message_content = "";
String userId_FirstActivity = "";
String date = "";
String report = "";
// Cursor DECLARATION//
Cursor c = null;
Cursor cur = null;
Cursor curMessageTable = null;
Cursor curMessageName = null;
Cursor curMainActivity = null;
Cursor curTimeReportMessage = null;
public AsyncSecondActivity(JSONObject jsonobj) {
Log.v(TAG, "Value of BULK in AsyncSecondActivity (GETSET METHOD) "
+ jsonobj);
}
#Override
protected Void doInBackground(Void... params) {
try{
DefaultHttpClient httpClientInstance = GetHttpClient
.getHttpClientInstance();
HttpPost httpPostRequest = new HttpPost(URL_);
Log.v(TAG, "The url is " + URL_);
StringEntity se;
se = new StringEntity(jsonobj.toString());
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");
long t = System.currentTimeMillis();
HttpResponse response = (HttpResponse) httpClientInstance
.execute(httpPostRequest);
Log.i(TAG,
"HTTPRESPONSE RECIEVED in "
+ (System.currentTimeMillis() - t) + "ms");
resultString = convertStreamToString(response.getEntity()
.getContent());
// Log.v(TAG , "The response is " +resultString);
jsonobj = new JSONObject(resultString);
JSONObject sync_reponse = jsonobj.getJSONObject("syncresponse");
String synckey_string = sync_reponse.getString("synckey");
JSONArray createdtrs_array = sync_reponse
.getJSONArray("createdtrs");
JSONArray modtrs_array = sync_reponse.getJSONArray("modtrs");
// -----HANDLING MODTRS-----//
for (int n = 0; n < modtrs_array.length(); n++) {
JSONObject object = modtrs_array.getJSONObject(n);
String newcompanyID_mod = object.getString("companyid");
String newusername_mod = object.getString("username");
String newdate_mod = object.getString("date");
String newclientid_mod = object.getString("clientid");
String newprojectid_mod = object.getString("projectid");
String newniv1_mod = object.getString("niv1");
String newniv2_mod = object.getString("niv2");
String newworktypeid_mod = object.getString("worktypeid");
String newtimetypeid_mod = object.getString("timetypeid");
String newhours_mod = object.getString("hours");
String newcomment_mod = object.getString("comment");
String newprivatecomment_mod = object
.getString("privatecomment");
String newopen_mod = object.getString("open");
if ((object.has("message"))) {
JSONObject messaget = object.getJSONObject("message");
String newtype = object.getJSONObject("message")
.getString("type");
String newcontent = object.getJSONObject("message")
.getString("content");
GetSetMethod objSample = new GetSetMethod();
objSample.setnewclientid_mod(newclientid_mod);
objSample.setnewusername_mod(newusername_mod);
objSample.setnewdate_mod(newdate_mod);
objSample.setnewprojectid_mod(newprojectid_mod);
objSample.setNewniv1(newniv1_mod);
objSample.setNewniv2(newniv2_mod);
objSample.setNewworktypeid(newworktypeid_mod);
objSample.setNewtimetypeid(newtimetypeid_mod);
objSample.setNewhours(newhours_mod);
objSample.setNewcomment(newcomment_mod);
objSample.setNewopen(newopen_mod);
objSample.setNewprivatecomment(newprivatecomment_mod);
}
}
JSONArray deletedtrs_array = sync_reponse
.getJSONArray("deletedtrs");
// -----------------------HANDLING
// DELETEDTRS------------------------//
for (int n = 0; n < deletedtrs_array.length(); n++) {
JSONObject object = deletedtrs_array.getJSONObject(n);
String newUserName = object.getString("username");
String newCompanyId = object.getString("companyid");
String newDate = object.getString("date");
String newReportId = object.getString("reportid");
}
JSONArray newtrs_array = sync_reponse.getJSONArray("newtrs");
// -----------------------HANDLING
// NEWTRS----------------------------//
GetSetMethod objSample = null;
for (int n = 0; n < newtrs_array.length(); n++) {
JSONObject object = newtrs_array.getJSONObject(n);
String newcompanyid = object.getString("companyid");
String newusername = object.getString("username");
String newdate = object.getString("date");
String newClientId = object.getString("clientid");
String newprojectId = object.getString("projectid");
String newniv1 = object.getString("niv1");
String newniv2 = object.getString("niv2");
String newworktypeid = object.getString("worktypeid");
String newtimetypeid = object.getString("timetypeid");
String newhours = object.getString("hours");
String newcomment = object.getString("comment");
String newprivatecomment = object
.getString("privatecomment");
String newopen = object.getString("open");
String newreportid = object.getString("reportid");
String newcontent_mod = "";
String newtype_mod = "";
if ((object.has("message"))) {
JSONObject message = object.getJSONObject("message");
newtype_mod = object.getJSONObject("message")
.getString("type");
newcontent_mod = object.getJSONObject("message")
.getString("content");
// objSample = new GetSetMethod();
// objSample.setnewcontent_mod(newcontent_mod);
// objSample.setnewtype_mod(newtype_mod);
}
objSample = new GetSetMethod();
objSample.setNewcompanyid(newcompanyid);
objSample.setNewusername(newusername);
objSample.setNewdate(newdate);
objSample.setNewClientId(newClientId);
objSample.setNewprojectId(newprojectId);
objSample.setNewniv1(newniv1);
objSample.setNewniv2(newniv2);
objSample.setNewworktypeid(newworktypeid);
objSample.setNewtimetypeid(newtimetypeid);
objSample.setNewhours(newhours);
objSample.setNewcomment(newcomment);
objSample.setNewprivatecomment(newprivatecomment);
objSample.setNewopen(newopen);
objSample.setNewreportid(newreportid);
if ((newcontent_mod) != null || (newtype_mod) != null) {
objSample.setnewcontent_mod(newcontent_mod);
objSample.setnewtype_mod(newtype_mod);
}
bulk.add(objSample);
objSample.getNewClientId();
for (int i = 0; i < objVector.size(); i++) {
GetSetMethod objtest = new GetSetMethod();
objtest = (GetSetMethod) objVector.get(i);
objtest.getNewClientId();
objtest.getNewcompanyid();
}
}
//new AsyncSecondActivity(bulk).execute();
// -----------------------HANDLING
// SCHEMA-------------------------//
JSONArray schema_array = sync_reponse.getJSONArray("schema");
for (int n = 0; n < schema_array.length(); n++) {
JSONObject object = schema_array.getJSONObject(n);
String new_yearmonth = object.getString("yearmonth");
String new_hoursperday = object.getString("hoursperday");
}
} catch(JSONException e){
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
HashMap<String, String> recordExist = new HashMap<String, String>();
userHelper.openDatabase();
useradapter_TimeReportTable.openDatabase();
useradapterMessageTable.openDatabase();
useradapterMessageTypeTable.openDatabase();
useradapterTimeReportMessage.openDatabase();
curMainActivity = userHelper.retrieveUserId();
cur = useradapter_TimeReportTable.getUniqueRecordsId();
curMessageTable = useradapterMessageTable.getMessageTable();
curMessageName = useradapterMessageTypeTable.getMessageTypeId();
for (int i = 0; i < bulk.size(); i++) {
GetSetMethod objtest = bulk.get(i);
this.newcompanyid1 = objtest.getNewcompanyid();
this.newusername1 = objtest.getNewusername();
this.newworktypeid1 = objtest.getNewworktypeid();
this.newniV2 = objtest.getNewniv2();
this.newniV1 = objtest.getNewniv1();
this.newdate1 = objtest.getNewdate();
this.newClientId1 = objtest.getNewClientId();
this.newprojectId1 = objtest.getNewprojectId();
this.newtimetypeid1 = objtest.getNewtimetypeid();
this.newhours1 = objtest.getNewhours();
this.newcomment1 = objtest.getNewcomment();
this.newprivatecomment1 = objtest.getNewprivatecomment();
this.newopen1 = objtest.getNewopen();
this.newreportid1 = objtest.getNewreportid();
this.message_content = objtest.getnewcontent_mod();
this.messageType_System = objtest.getnewtype_mod();
concatCursorCompare = date + "-" + report;
//Log.v("Line number 408: SecondActivity", "Value: " + date);
//Log.v("Line number 409: SecondActivity", "Value: " + report);
recordExist.put(concatCursorCompare, concatCursorCompare);
compareId = objtest.getNewdate() + "-"
+ objtest.getNewreportid();
if (!recordExist.containsValue(compareId)) {
long id = useradapter_TimeReportTable
.insertIntoDatabase(newcompanyid1,
newusername1, newdate1, newClientId1,
newprojectId1, newniV1, newniV2,
newworktypeid1, newtimetypeid1,
newhours1, newcomment1,
newprivatecomment1, newopen1,
newreportid1, userId_FirstActivity);
}
if (cur.moveToFirst()) {
do {
date = cur.getString(cur.getColumnIndexOrThrow("dateId"));
report = cur.getString(cur.getColumnIndexOrThrow("reportId"));
}
while(cur.moveToNext());
}
if (curMessageName.moveToFirst()) {
messageTypeId = curMessageName.getString(curMessageName
.getColumnIndex("messageTypeId"));
}
else {
if (messageType_System != null && messageType_System != "") {
long ins_msg_typ_tbl = useradapterMessageTypeTable
.insertintoMessageTypeName(messageType_System);
curMessageName = useradapterMessageTypeTable.recordExistsmessageTypeTable(messageType_System);
if (curMessageName.moveToFirst()) {
messageTypeId = curMessageName.getString(curMessageName
.getColumnIndex("messageTypeId"));
}
}
}
if (curMainActivity.moveToFirst()) {
userId_FirstActivity = curMainActivity
.getString(curMainActivity
.getColumnIndexOrThrow("userId"));
}
concatCursorCompare = date + "-" + report;
Log.v("Line number 408: SecondActivity", "Value: " + date);
Log.v("Line number 409: SecondActivity", "Value: " + report);
recordExist.put(concatCursorCompare, concatCursorCompare);
compareId = objtest.getNewdate() + "-"
+ objtest.getNewreportid();
}
for (int i = 0; i < bulk.size(); i++) {
GetSetMethod objtest = bulk.get(i);
this.newcompanyid1 = objtest.getNewcompanyid();
this.newusername1 = objtest.getNewusername();
this.newworktypeid1 = objtest.getNewworktypeid();
this.newniV2 = objtest.getNewniv2();
this.newniV1 = objtest.getNewniv1();
this.newdate1 = objtest.getNewdate();
this.newClientId1 = objtest.getNewClientId();
this.newprojectId1 = objtest.getNewprojectId();
this.newtimetypeid1 = objtest.getNewtimetypeid();
this.newhours1 = objtest.getNewhours();
this.newcomment1 = objtest.getNewcomment();
this.newprivatecomment1 = objtest.getNewprivatecomment();
this.newopen1 = objtest.getNewopen();
this.newreportid1 = objtest.getNewreportid();
this.message_content = objtest.getnewcontent_mod();
this.messageType_System = objtest.getnewtype_mod();
try {
compareId = objtest.getNewdate() + "-"
+ objtest.getNewreportid();
if(message_content != null && message_content !=""){
long insertMessageTable = useradapterMessageTable.insertintoMessageTable(messageTypeId,message_content);
}
if(message_content != null && message_content !="" && report!=null && report != ""){
long insertTimeReportMessage = useradapterTimeReportMessage.insertintoTimeReportMessgeTable(report, messageTypeId, date);
}
}catch (Exception e) {
e.printStackTrace();
} finally {
if (curMainActivity != null) {
curMainActivity.close();
curMainActivity = null;
}
if (c != null) {
c.close();
c = null;
}
if (cur != null) {
cur.close();
cur = null;
}
if (curMessageTable != null) {
curMessageTable.close();
curMessageTable = null;
}
if (curMessageName != null) {
curMessageName.close();
curMessageName = null;
}
if(curTimeReportMessage != null){
curTimeReportMessage.close();
curTimeReportMessage = null;
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) throws SQLiteException {
super.onPostExecute(result);
PD.dismiss();
userHelper.closeDatabase();
useradapter_TimeReportTable.closeDatabase();
useradapterMessageTable.closeDatabase();
useradapterMessageTypeTable.closeDatabase();
useradapterTimeReportMessage.closeDatabase();
Toast.makeText(getApplicationContext(),
"Welcome " + getIntent().getStringExtra("regName"),
Toast.LENGTH_LONG).show();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
PD = new ProgressDialog(Secondactivity.this);
PD.setTitle("Please wait");
PD.setMessage("Updating records");
PD.show();
} catch (Exception progressDialog) {
progressDialog.printStackTrace();
}
}
}
}
To put in simple terms I will take a username password and insert it into the database. After I get a JSON response from webservice (got by sending the username and password) I parse the JSON object to a string and then insert it into the database.
In the second activity I obtain a JSON response that I parse and convert the input to a string. I then insert the JSON response into their respective databases.
Emulator is slow - normal device could be much faaster. One potential source for delay woud be UserHelper Object creation - you provided no source code for it. You also omited code for onResume() methods of your activities. Best way to find where performance has gone, would be to perform profiling run with ddms.
I have an application where I fetch data from http server & set data to activity.
for fetching data from server it takes time. so i want to give an progress dialog there.
I did that but problem is that progressdialog is coming but its not rotating(only constant).
Plz anybody tell me how it came like this!
Below is my code,
private void setupViews()
{
imgRestro = (ImageView) findViewById(R.id.imageResturant);
tvRestroName = (TextView) findViewById(R.id.tvRestroName);
tvRestroAddr = (TextView) findViewById(R.id.tvRestroAddr);
tvRestroArea = (TextView) findViewById(R.id.tvRestroArea);
tvRestroCity = (TextView) findViewById(R.id.tvRestroCity);
tvRestroPhone = (TextView) findViewById(R.id.tvRestroPhone);
tvRestroRating = (TextView) findViewById(R.id.tvRestroRating);
tvRestroCuisines = (TextView) findViewById(R.id.tvRestroCuisines);
tvRestroAttr = (TextView) findViewById(R.id.tvRestroAttributes);
}
//to execute url
private String executeHttpGet(String URL) throws Exception {
URL url = null;
StringBuffer strBuf = null;
BufferedReader read = null;
HttpURLConnection httprequest = null;
try {
url = new URL(URL);
httprequest = (HttpURLConnection) url.openConnection();
httprequest.setRequestMethod("GET");
httprequest.setDoInput(true);
httprequest.setDoOutput(true);
httprequest.setConnectTimeout(5000); //time for before connect
httprequest.setRequestProperty("Content-Type",
"text/plain; charset=utf-8");
//httprequest.setReadTimeout(15000); //time for after connect
read = new BufferedReader(new InputStreamReader(
httprequest.getInputStream()));
strBuf = new StringBuffer();
String line = "";
while ((line = read.readLine()) != null) {
strBuf.append(line).append("\n");
}
} catch (IOException ex) {
} finally {
try {
httprequest.disconnect();
read.close();
} catch (Exception ex) {
}
}
return strBuf.toString();
}
//to assign all the info from json to activity textview or imageview
private void examineJSONFile() {
try {
String str = "";
page = executeHttpGet(url);
Log.i("hello", str.toString());
JSONObject topobj = new JSONObject(page);
JSONObject innerobj = topobj.getJSONObject("restarutant");
tvRestroName.setText("Restaurant "+innerobj.getString("name"));
String photoURL = innerobj.getString("photo");
URI uri = new URI(photoURL);
Bitmap bmp = loadBitmap(photoURL);
System.out.println("str ;" + photoURL + " uri " + uri);
imgRestro.setImageBitmap(Bitmap.createScaledBitmap(bmp, 300, 300,true));
tvRestroAddr.setText("Address: " + innerobj.getString("address"));
tvRestroArea.setText("Area: " + innerobj.getString("area"));
tvRestroCity.setText("City: " + innerobj.getString("city"));
JSONArray location = innerobj.getJSONArray("location");
String lat = location.get(0).toString();
String lng = location.get(1).toString();
latitude = Double.valueOf(lat.trim()).doubleValue();
longitude = Double.valueOf(lng.trim()).doubleValue();
System.out.println("Lat :" + latitude + " Long :" + longitude);
JSONArray phone = innerobj.getJSONArray("phone");
tvRestroPhone.setText("Phone: " + phone.get(0).toString() + " ,"
+ phone.get(1).toString());
tvRestroRating.setText("Rating: " + innerobj.getString("rating"));
JSONArray cuisines = innerobj.getJSONArray("cuisines");
tvRestroCuisines.setText("Cuisines: " + cuisines.get(0).toString()
+ " ," + cuisines.get(1).toString());
JSONArray attributes = innerobj.getJSONArray("attributes");
tvRestroAttr.setText("Attributes: " + attributes.get(0).toString()
+ " ," + attributes.get(1).toString() + " ,"
+ attributes.get(2).toString());
Log.i("hello", str.toString());
} catch (Exception je) {
tvRestroAddr.setText("Error w/file: " + je.getMessage());
}
}
// to get image from url in form of bitmap
private static Bitmap loadBitmap(String url) {
URL myFileUrl = null;
InputStream is = null;
try {
myFileUrl = new URL(url);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream();
Log.i("im connected", "Download");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return BitmapFactory.decodeStream(is);
}
//for progressdialog
private class DownloadTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog = new ProgressDialog(InfoActivity.this);
protected void onPreExecute() {
System.out.println("In onPreExecute ");
dialog.setTitle("Loading..");
dialog.setMessage("Downloading source..");
dialog.setProgress(100);
dialog.setMax(5000);
dialog.show();
}
protected Void doInBackground(Void... unused) {
//examineJSONFile();
System.out.println("In doInBackground ");
return null;
}
protected void onPostExecute(Void unused) {
System.out.println("In onPostExecute ");
dialog.dismiss();
examineJSONFile();
}
Plz have a look and give the answer.
Thank you
You should override onProgressUpdate() method in AsyncTask and change your dialog's value there. You can send your progress value to the dialog via publishProgress() method from doInBackground(). Hope this helps.
Try using Async task as shown below:
try{
class test extends AsyncTask{
TextView tv_per;
int mprogress;
Dialog UpdateDialog = new Dialog(ClassContext);
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
mprogress = 0;
UpdateDialog.setTitle(getResources().getString(R.string.app_name));
UpdateDialog.setContentView(R.layout.horizontalprogressdialog);
TextView dialog_message = (TextView)UpdateDialog.findViewById(R.id.titleTvLeft);
tv_per = (TextView)UpdateDialog.findViewById(R.id.hpd_tv_percentage);
dialog_message.setText(getResources().getString(R.string.dialog_retrieving_data));
dialog_message.setGravity(Gravity.RIGHT);
UpdateDialog.setCancelable(false);
UpdateDialog.show();
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Object... values) {
// TODO Auto-generated method stub
ProgressBar update = (ProgressBar)UpdateDialog.findViewById(R.id.horizontalProgressBar);
update.setProgress((Integer) values[0]);
int percent = (Integer) values[0];
if(percent>=100)
{
percent=100;
}
tv_per = (TextView)UpdateDialog.findViewById(R.id.hpd_tv_percentage);
tv_per.setText(""+percent);
}
#Override
protected Object doInBackground(Object... params) {
// TODO Auto-generated method stub
//your code
}
super.onPostExecute(result);
UpdateDialog.dismiss();
}
}
new test().execute(null);
}
catch(Exception e)
{
e.printStackTrace();
}