i am trying to implement sample JSON data App that Gets JSON data from server
i am Getting complete JSON file whats wrong with my coding ?
i am following an youtube tutorial but he did successfully but i am getting complete JSON File
this is JSON server side file
{
"movies" :[
{
"movie" : "Avenger",
"year" : 2012
}
]
}
and this is code from android app
package com.yog.jsonparser;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.URLUtil;
import android.widget.Button;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
TextView tvData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnHit = (Button) findViewById(R.id.btnHit);
tvData = (TextView)findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JSONTask().execute("http://myDomainName.com/getData.txt");
}
});
}
public class JSONTask extends AsyncTask<String,String,String>{
HttpURLConnection connection = null;
BufferedReader reader = null;
URI url;
StringBuffer buffer;
#Override
protected String doInBackground(String... params){
try{
//URL OF REQUESTED PAGE
url=new URI(params[0]);
connection = (HttpURLConnection) (new URL(params[0]).openConnection());
connection.connect();
InputStream stream=connection.getInputStream();
reader=new BufferedReader(new InputStreamReader(stream));
buffer=new StringBuffer();
String line;
while((line =reader.readLine())!=null){
buffer.append(line);
}
String finalJSON=buffer.toString();
JSONObject parentOject = new JSONObject(finalJSON);
JSONArray parentArray = parentOject.getJSONArray("movies");
JSONObject finalObject= parentArray.getJSONObject(0);
String movieName= finalObject.getString("movie");
int year=finalObject.getInt("year");
return movieName + "-" + year;
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection !=null){
connection.disconnect();
}
try{
if(reader !=null){
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
tvData.setText(buffer.toString());
}
}
}
current Output :
{"movies" :[{ "movie" : "Avenger","year" : 2012}]}
Expected output :
Avenger
2012
Change your onPostExecute method as below.
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
tvData.setText(s);
}
Here s will be return statement of doInBackground. "movieName + "-" + year;"
You are getting {"movies" :[{ "movie" : "Avenger","year" : 2012}]} in the TextView because you are setting the buffer's output to the TextView. Change your onPostExecute like this:
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(s != null){
tvData.setText(s);
}else{
//// Some error occurred
tvData.setText(buffer.toString());
}
}
Related
I have an activity containing one edit-text, button and Textview.
Now I want if someone enters Java in edit-text then its info to be
filled in Text View. Here is my JSON. I have also included my .java file along with it.
{
"compscience": [
{
"bookname": "java",
"row": "1",
"column": "1"
},
{
"bookname": "cns",
"row": "2",
"column": "2"
},
{
"bookname": "rdbms",
"row": "3",
"column": "3"
},
{
"bookname": "daa",
"row": "4",
"column": "4"
}
]
}
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
public class act1 extends AppCompatActivity {
EditText subname;
Button fetch;
static String ab,single="";
public static String c;
static TextView data;
fetchdata process;
StringBuffer response ;
void init()
{
subname = findViewById(R.id.subname);
ab = subname.toString();
fetch = findViewById(R.id.button);
data=findViewById(R.id.result);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_act1);
init();
}
public void fetch(View view)
{
process = new fetchdata();
process.execute();//it will start do in background
}
class fetchdata extends AsyncTask {
#Override
protected Object doInBackground(Object[] objects) {
response = new StringBuffer();
try {
URL url = new URL("https://api.myjson.com/bins/c1054");
URLConnection connection =url.openConnection();
InputStream inputStream = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
BufferedReader buffer = new BufferedReader(reader);
String line = "";
while((line = buffer.readLine()) != null) {
response.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
try {
JSONArray array=new JSONArray("respnse");
for(int i=0;i<array.length();i++)
{
JSONObject obj=array.getJSONObject(i);
if(ab.equals(obj.getString("booknmae")))
{
single = single +obj.getString("row");
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
act1.data.setText(single);
}
}
}
Fist of all, you need to understand how JSONObject and JSONArray work, your json response is JSONObject and inside it there is key with name compscience have JSONArray as value.
try this:
try {
JSONObject respJson = new JSONObject(response.toString());
JSONArray array = respJson.getJSONArray("compscience");
for(int i=0;i<array.length();i++)
{
JSONObject obj=array.getJSONObject(i);
if(ab.equals(obj.getString("booknmae")))
{
single = single +obj.getString("row");
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I am new to android. I am learning android networking now. I am trying to create a connection with HttpURLConnection to track the response code as 200,
but I am getting IllegalArgumentException. I am doing this with Async task but couldn't rectify. Any help would be appreciated.
Here is my code :
package com.movies.usman.moviesmesh;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new CheckConnectionStatus().execute("http://google.com");
}
class CheckConnectionStatus extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... params) {
URL url = null;
try {
url = new URL(params[0]);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//Log.i("Reponse: ", String.valueOf(urlConnection.getResponseCode()));
return String.valueOf(urlConnection.getResponseCode());
} catch (IOException e) {
Log.e("Error: ", e.getMessage(), e);
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
text.setText(s);
}
}
}
You should initialize your TextView in onCreate
text = (TextView) findViewById(R.id.yourViewId);
before of
new CheckConnectionStatus().execute("http://google.com");
/* Here the last parameter is taken from edittext but it is not adding input from
edittext */ Please check:
http://103.75.33.98/BPService/GetAllBPService.svc/GetSalesPersonNo/CBS/NOIDA/ADMIN
package com.example.administrator.spinnerval;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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;
import java.util.List;
public class SalesActivity extends AppCompatActivity {
StringBuffer buffer = new StringBuffer();
List<String> salesPeName = new ArrayList<String>();
HttpURLConnection connection;
BufferedReader reader;
ProgressDialog pdLoading;
String username = "CBS";
String password = "NOIDA";
String city="" ;
String myurl;
ArrayAdapter adapter;
URL url;
AutoCompleteTextView acTextView;
//String url="http://103.75.33.98/BPService/GetAllBPService.svc/GetSalesPersonNo/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sales);
acTextView = (AutoCompleteTextView) findViewById(R.id.autoComplete2);
acTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selection = (String)parent.getItemAtPosition(position);
// city=(String)parent.getItemAtPosition(position);
city=acTextView.getText().toString();
}
});
myurl="http://103.75.33.98/BPService/GetAllBPService.svc/GetSalesPersonNo";
String res = new StringBuilder(14).append(myurl).append("/").append(username).append("/").append(password).toString();
String result=new StringBuilder(14).append(res).append("/").append(city).toString();
try {
url=new URL(result);
Log.d("url",url.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
adapter = new
ArrayAdapter(this, android.R.layout.simple_list_item_1, salesPeName);
//acTextView.setAdapter(adapter);
new SalesTask().execute(city);
}
private class SalesTask extends AsyncTask<String,String,String> {
#Override
protected String doInBackground(String... params) {
try {
//url = new URL("http://103.75.33.98/BPService/GetAllBPService.svc/GetSalesPersonNo/"+username+"/"+password+"/"+city);
connection = (HttpURLConnection) url.openConnection();
Log.e("url reference value",url.toString());
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
String line = "";
Log.d("bufferData", buffer.toString());
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
String jsonString = buffer.toString();
// Log.e("Final Json that we have", jsonString);
JSONObject obj = null;
try {
obj = new JSONObject(jsonString);
JSONObject obj1 = obj.getJSONObject("GetBPSalesPersonResult");
JSONArray jArray = obj1.getJSONArray("BPResult");
for (int i = 0; i <= jArray.length(); i++) {
salesPeName.add(jArray.getJSONObject(i).getString("SALES_PERSON_NO"));
Log.e("Location",salesPeName.toString());
acTextView.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Logcat is printing url as :
url: http://103.75.33.98/BPService/GetAllBPService.svc/GetSalesPersonNo/CBS/NOIDA/
Not sure if I understood your question correctly, but you are adding undeclared variables to the url. I think it should be:
URL url = new URL("http://103.75.33.98/BPService/GetAllBPService.svc/GetSalesPersonNo/"+cbs+"/"+city+"/"+saleP);
The problem is that you create the Url on in onCreate, at witch time city="", and you change the city in onItemClick: city=acTextView.getText().toString(), you need to generate the URL in onItemClick and call new SalesTask().execute(city); not right away
acTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selection = (String)parent.getItemAtPosition(position);
city = acTextView.getText().toString();
url = new URL(new StringBuilder(myurl).append("/").append(username).append("/").append(password).append("/").append(city).toString());
new SalesTask().execute(city);
}
});
I'm trying to get it so my app can read the words from my textfile separated by a carriage enter and spit them back out from a String array. My app starts up then just gives me a blank page which is pretty frustrating. Here is my code:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.Vector;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView helloTxt= (TextView)findViewById(R.id.hellotxt);
ArrayList<String> list = new ArrayList<String>();
try {
InputStream is = getResources().openRawResource(R.raw.test);
if (is != null) {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader buffythevampireslayer = new BufferedReader(isr);
String line;
do {
line = buffythevampireslayer.readLine();
list.add(line);
} while (line != null);
}
is.close();
} catch (Exception ex) {
}
String[] wordsArray=new String[list.size()];
list.toArray(wordsArray);
Thread timer=new Thread(); {
for (int c=0;c<list.size();c++){
helloTxt.setText(wordsArray[c]);
System.out.println("TEXTSET");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
timer.start();
}
}
I'd really appreciate it if anyone could help, thanks so much!!!
EDIT::::
After getting some help in this post, I now have the working app! Thanks so much! Here is the new code:
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.Vector;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.app.Activity;
import android.content.res.AssetManager;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ReadAndUpdateTextTask readAndUpdateTextTask = new ReadAndUpdateTextTask();
readAndUpdateTextTask.execute();
}
class ReadAndUpdateTextTask extends AsyncTask<Void, String, String> {
public String currentString = "";
String line="";
InputStream isr;
#Override
protected void onPreExecute() {
isr = getResources().openRawResource(R.raw.test);
}
#Override
protected String doInBackground(Void... params) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(isr));
while ((line = reader.readLine())!= null) {
currentString += line + "\n";
publishProgress(currentString);
// I don't think you really need this but you want a sleep for 5000 ms
SystemClock.sleep(5000);
}
isr.close();
} catch (Exception ex) {
}
return currentString;
}
#Override
protected void onProgressUpdate(String... currentString) {
TextView helloTxt= (TextView)findViewById(R.id.hellotxt);
helloTxt.setText(currentString[0]);
}
#Override
protected void onPostExecute(String result) {
TextView helloTxt= (TextView)findViewById(R.id.hellotxt);
helloTxt.setText(result);
}
}
}
I don't know if this will solve anything, but you can try declaring your List as shown in Oracle's documentation. I will look further in a bit.
List<String> list = new ArrayList<String>();
if it's not a typo, your problem is here:
String[] wordsArray=new String[list.size()];
list.toArray(wordsArray);
it should be:
String[] wordsArray = list.toArray( new String[0] );
otherwise the array is filled with nulls
First, you need to store your text file in the assets folder
then you need to call the AssetManager to get the assets in your assets folder
AssetManager assetManager = getAssets();
InputStream inputStream = null;
surround these statements with a try block, in case the file is not found in the stated path
inputStream = assetManager.open("texts/sample.txt"); // path is relative to the assets folder
ByteArrayOutputStream bytesOutputStream = new ByteArrayOutputStream();
byte[] bytes = new byte[4096];
int length = 0;
read the the bytes and write them in an output stream
while((length = inputStream.read(bytes)) > 0)
bytesOutputStream.write(bytes,0,length);
create a new String, use the constructor with the byteOutputStream
encode it with UTF8(assuming there wont be any chinese, japanese, etc characters)
See this for more details about UTF Details
String yourString = new String(bytesOutputStream.toByteArray(), "UTF8");
Java String class has a method "split", which takes a regex as a parameter
it splits the string and stores it into a single element in an array everytime it encounters a new line
in your case, use '\n' which stands for new line
String[] yourStringArray = yourString.split("\n");
Surround everything with a try-catch clause (IOException), which is thrown in case file is not found
you can now use yourStringArray as
textView.setText(yourStringArray[index]);
You got a blank screen because you have a sleep at your main UI thread. Do reading the file in an AsyncTask and publish its process.
Your onCreate method should look like this:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ReadAndUpdateTextTask readAndUpdateTextTask = new ReadAndUpdateTextTask();
readAndUpdateTextTask.execute();
}
class ReadAndUpdateTextTask extends AsyncTask<Void, String, String> {
InputStream isr;
#Override
protected void onPreExecute() {
isr = getResources().openRawResource(R.raw.test);
}
#Override
protected String doInBackground(Void... params) {
try {
String currentString = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(isr));
while ((line = reader.readLine())!= null) {
currentString += line + "\n";
publishProgress(currentString);
// I don't think you really need this but you want a sleep for 5000 ms
SystemClock.sleep(5000);
}
isr.close();
} catch (Exception ex) {
}
return currentString;
}
#Override
protected void onProgressUpdate(String... currentString) {
TextView helloTxt= (TextView)findViewById(R.id.hellotxt);
helloTxt.setText(currentString[0]);
}
#Override
protected void onPostExecute(String result) {
TextView helloTxt= (TextView)findViewById(R.id.hellotxt);
helloTxt.setText(result);
}
}
}
I am sending some information from my application to server and waiting for the response. Before i send i set my textview for message to display "processing request" and after getting response i display a different message.
This processing message is not getting displayed. Is it beacuse the UI is getting blocked due to other operation.
How to handle this. Threading is not giving correct result as need to display the response.
SO that involve UI in the thread .
package com.PandG.app.android.activities;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.PandG.app.android.R;
import com.PandG.app.android.dataAccess.SettingsDBAccess;
import com.PandG.app.android.entity.Job;
import com.PandG.app.android.entity.Settings;
import com.PandG.app.android.services.JobsManager;
import com.lib.android.Utils.Utils;
import com.lib.android.activity.BaseActivity;
import com.lib.android.dataAccess.DatabaseManager;
public class JobCheckoutActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setViewContent();
}
private void setViewContent() {
Settings setting = getSettings();
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.job_checkout);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.customtitle);
//new DataProcess().execute(null);
TextView text1 = (TextView)findViewById(R.id.checkoutmessage);
text1.setText("Processiong Job Cart ...");
if(setting!=null){
TextView text2 = (TextView)findViewById(R.id.checkoutheading);
text2.setVisibility(View.GONE);
Button homeButton = (Button)findViewById(R.id.gohome);
homeButton.setVisibility(View.GONE);
JSONObject jobObject =encodeData(setting);
sendDataToServer(jobObject);
}
}
private void sendDataToServer(JSONObject jobObject) {
TextView text1 = (TextView)findViewById(R.id.checkoutmessage);
text1.setText("Processiong Job Cart ...");
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
// Limit
HttpResponse response;
try {
HttpPost post = new HttpPost(Utils.getPostUrl());
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("orderparameters",
jobObject.toString()));
Log.i("Job ORDER", jobObject.toString());
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = client.execute(post);
checkResponseFromServer(response);
ClearCart();
} catch (Exception e) {
Log.w("error", "connection failed");
Toast.makeText(this, "Order not placed due to connection error",
Toast.LENGTH_LONG);
e.printStackTrace();
}
}
private void ClearCart() {
JobsManager.JobsCartList.clear();
}
private void checkResponseFromServer(HttpResponse response) {
try {
if (response != null) {
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
String line;
StringBuffer buffer = new StringBuffer();
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
in.close();
JSONObject jsonResponse = new JSONObject(buffer.toString());
Log.i("Status", jsonResponse.getString("status"));
Log.i("Status", jsonResponse.getString("message"));
Log.i("Status", jsonResponse.getString("debug"));
TextView text1 = (TextView)findViewById(R.id.checkoutheading);
text1.setVisibility(View.VISIBLE);
TextView text = (TextView) findViewById(R.id.checkoutmessage);
if (jsonResponse.getString("status").equals("SUCC")) {
text.setText( Html.fromHtml(getString(R.string.checkout_body1)));
} else
text.setText(jsonResponse.getString("message")
+ jsonResponse.getString("debug"));
}
} catch (Exception ex) {
}
}
private JSONObject encodeData(Settings setting) {
JSONObject jobObject = new JSONObject();
try {
JSONObject jobject = new JSONObject();
jobject.put("name", setting.getName());
jobject.put("email", setting.getEmail());
jobject.put("phone", setting.getPhone());
jobject.put("school", setting.getSchool());
jobject.put("major", setting.getMajor());
jobObject.put("customer", jobject);
JSONArray jobsarray = new JSONArray();
for (Job job : JobsManager.JobsCartList) {
JSONObject jobEntry = new JSONObject();
jobEntry.put("jobtitle",job.getTitle());
jobEntry.put("qty","1");
jobsarray.put(jobEntry);
}
jobObject.put("orders", jobsarray);
} catch (JSONException ex) {
}
return jobObject;
}
private Settings getSettings() {
SettingsDBAccess settingsDBAccess = new SettingsDBAccess(
DatabaseManager.getInstance());
Settings setting = settingsDBAccess.getSetting();
if (setting==null){
startActivityForResult((new Intent(this,SettingsActivity.class)),Utils
.getDefaultRequestCode());
}
return setting;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Settings setting = new SettingsDBAccess(
DatabaseManager.getInstance()).getSetting();
if(setting!=null){
JSONObject jobObject = encodeData(setting);
sendDataToServer(jobObject);
}
}
/* private class DataProcess extends AsyncTask {
#Override
protected void onPostExecute(Object result) {
}
#Override
protected Object doInBackground(Object... arg0) {
processDataandsend();
return null;
}
private void processDataandsend() {
Settings setting = getSettings();
if(setting!=null){
TextView text2 = (TextView)findViewById(R.id.checkoutheading);
text2.setVisibility(View.GONE);
Button homeButton = (Button)findViewById(R.id.gohome);
homeButton.setVisibility(View.GONE);
JSONObject jobObject =encodeData(setting);
sendDataToServer(jobObject);
}
}
} */
}
You should not perform HTTP-work on the UI-thread. Instead use AsyncTask
In your AsyncTask you are only allowed to update the UI in two places:
#Override
protected void onPreExecute()
TextView.setText("Beginning HTTP-work..Please wait");
{
and
#Override
protected void onPostExecute(Void v) {
TextView.setText("Done..SUCCESS!");
}
Use these two to update the UI before and after the HTTP-work has been done.
Long operations must be in background. Best way to implement this on Android, use AsyncTask, for more information: http://developer.android.com/reference/android/os/AsyncTask.html