How to display a particular entry from json in textview? - android

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();
}

Related

I have to add edittext input at city position and add it to url

/* 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);
}
});

JSONParser getting complete JSON file With curly brackets

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());
}
}

AsyncTask in Fragment not working and shows FATAL EXCEPTION: AsyncTask #1

The following code when run crashes my app. I am calling it in the MainActivity. When run it tells me:
FATAL EXCEPTION: AsyncTask #1 and directs me toward the ProgressDialog and Http Response Line
import android.app.Fragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import com.montel.senarivesselapp.model.ShowDataList;
import com.montel.senarivesselapp.model.Vessel;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
public class ShowallFragment extends Fragment {
//variables for JSON query
private static final String name ="vessel_name";
private static final String etad="eta_date";
private static final String etat="eta_time";
private static final String etbd="etb_date";
private static final String etbt="etb_time";
private static final String shippingName="shipping_agent_name";
private static final String v1 = "vessels";
private static final String v2 = "Vessel";
private ArrayList<Vessel> vList = new ArrayList<>();
private ArrayAdapter arrayAdapter = null;
private ListView listView = null;
private EditText et = null;
private ShowDataList ssadapter = null;
private View rootView;
public ShowallFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_showall, container, false);
setContentView(R.layout.fragment_showall);
setRetainInstance(true);
return rootView;
}
private void setContentView(int fragment_showall) {
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
//For getting the JSON schedule from server
class Schedule extends AsyncTask<String, String, String> {
ProgressDialog loadDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
//Show the loading dialog
loadDialog = new ProgressDialog(ShowallFragment.this);
loadDialog.setMessage("Please wait....");
loadDialog.setCancelable(false);
loadDialog.show();
}
#Override
protected String doInBackground(String... uri) {
BufferedReader input = null;
String data = null;
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(new HttpGet("http://"));
StatusLine stline = response.getStatusLine();
if (stline.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
data = out.toString();
out.close();
} else {
response.getEntity().getContent().close();
throw new IOException(stline.getReasonPhrase());
}
} catch (HttpResponseException he) {
he.printStackTrace();
} catch (ClientProtocolException cpe) {
cpe.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
return data;
} catch (Exception e) {
System.out.println(e);
}
}
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Fill the vList array
Log.d("POST EXECUTE", result.toString());
loadDialog.dismiss();
if (result != null) {
try {
JSONObject jo = new JSONObject(result);
JSONArray vessels = jo.getJSONArray(v1);
Log.d("VESSEL LOG", vessels.toString());
vList = new ArrayList();
for (int i = 0; i < vessels.length(); i++) {
JSONObject vv = vessels.getJSONObject(i);
Log.d("VESSEL NAME", vv.getJSONObject(v2).getString(name));
vList.add(new Vessel(vv.getJSONObject(v2).getString(name),
vv.getJSONObject(v2).getString(etad),
vv.getJSONObject(v2).getString(etat),
vv.getJSONObject(v2).getString(etbd),
vv.getJSONObject(v2).getString(etbt),
vv.getJSONObject(v2).getString(shippingName)));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
listView = (ListView) rootView.findViewById(R.id.dataShow);
listView.setAdapter(arrayAdapter);
ssadapter = new ShowDataList(ShowallFragment.this , vList);
listView.setAdapter(ssadapter);
}
}
}
SecurityException: Permission denied (missing INTERNET permission
So you should request INTERNET permission in your projects AndroidManifest.xml file. Add on the rigth place:
<uses-permission android:name="android.permission.INTERNET" />
in your onPostExecute() change the position of Log.d("POST EXECUTE", result.toString()); to be inside catch so your code will look like this:
catch (Exception ee) {
ee.printStackTrace();
}
catch (JSONException e) {
Log.d("POST EXECUTE", e.toString());
} // catch (JSONException e)

Android-Json parser not able to display data retrieved from back end

I am new to android. I am implementing a project in which I want to get the data from the back end and display on my android screen.
The Json I am trying to call is:-
[{"admin":null,"card_no":"8789","created_at":"2013-04-09T12:55:54Z","deleted":0,"email":"dfds#fgfd.com","entered_by":null,"first_name":"Gajanan","id":8,"last_name":"Bhat","last_updated_by":null,"middle_name":"","mobile":87981,"updated_at":"2013-04-13T05:26:25Z","user_type_id":null},{"admin":{"created_at":"2013-04-10T09:02:00Z","deleted":0,"designation":"Sr software Engineer","email":"admin#qwe.com","first_name":"Chiron","id":1,"last_name":"Synergies","middle_name":"Sr software Engineer","office_phone":"98789765","super_admin":false,"updated_at":"2013-04-10T12:03:04Z","username":"Admin"},"card_no":"66","created_at":"2013-04-08T09:47:15Z","deleted":0,"email":"rajaarun1991","entered_by":1,"first_name":"Arun","id":1,"last_name":"Raja\n","last_updated_by":1,"middle_name":"Nagaraj","mobile":941,"updated_at":"2013-04-08T09:47:15Z","user_type_id":1}]
My JsonParser.java is as follows:-
package com.example.library;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONArray jarray = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e("==>", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jarray = new JSONArray( builder.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jarray;
}
}
/* public void writeJSON() {
JSONObject object = new JSONObject();
try {
object.put("name", "");
object.put("score", new Integer(200));
object.put("current", new Double(152.32));
object.put("nickname", "Programmer");
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println(object);
}
*/
And my activity.java is as follows:-
package com.example.library;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class SecondActivity extends Activity
{
private Context context;
private static String url = "http://192.168.0.100:3000/users.json";
private static final String TAG_ID = "id";
private static final String TAG_FIRST_NAME = "first_name";
private static final String TAG_MIDDLE_NAME = "middle_name";
private static final String TAG_LAST_NAME = "last_name";
// private static final String TAG_POINTS = "experiencePoints";
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
ListView lv ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ProgressTask(SecondActivity.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
public ProgressTask(SecondActivity secondActivity) {
Log.i("1", "Called");
context = secondActivity;
dialog = new ProgressDialog(context);
}
/** progress dialog to show user that the backup is processing. */
/** application context. */
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
ListAdapter adapter = new SimpleAdapter(context, jsonlist,
R.layout.list_item, new String[] { TAG_ID, TAG_FIRST_NAME,
TAG_MIDDLE_NAME, TAG_LAST_NAME }, new int[] {
R.id.id, R.id.first_name, R.id.middle_name,
R.id.last_name });
setListAdapter(adapter);
// selecting single ListView item
lv = getListView();
}
private void setListAdapter(ListAdapter adapter) {
// TODO Auto-generated method stub
}
protected Boolean doInBackground(final String... args) {
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String id = c.getString(TAG_ID);
String first_name = c.getString(TAG_FIRST_NAME);
String middle_name = c.getString(TAG_MIDDLE_NAME);
String last_name = c.getString(TAG_LAST_NAME);
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_FIRST_NAME, first_name);
map.put(TAG_MIDDLE_NAME, middle_name);
map.put(TAG_LAST_NAME, last_name);
jsonlist.add(map);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
}
public ListView getListView() {
// TODO Auto-generated method stub
return null;
}
}
I am not able to show anything on the emulators for users,whereas I am able to fetch the data from the server
Actually in the project I want to display all the users present in the library.I am accessing the server which is on Ubuntu.
The following message is displayed on the console(Terminal):-
Started GET "/users.json" for 192.168.0.104 at 2013-05-05 22:05:01 -0700
Processing by UsersController#index as JSON
User Load (0.4ms) SELECT "users".* FROM "users" WHERE (users.deleted = 0) ORDER BY users.id DESC
Admin Load (0.3ms) SELECT "admins".* FROM "admins" WHERE "admins"."id" = 1 AND (admins.deleted = 0) ORDER BY admins.id DESC LIMIT 1
Completed 200 OK in 4ms (Views: 2.1ms | ActiveRecord: 0.6ms)
[2013-05-05 22:05:01] WARN Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true
However i am not able to display the data on the android screen/emulator.
Please help me with this.
I missed your setAdapterList()method.
Any error for your json pasers? and can you put your activity which is inherited from SecondActivity?
//modify getListView
public ListView getListView() {
// TODO Auto-generated method stub
listView = (ListView)findViewById(r.your.listview);
return listView;
}
//modify setListAdapter
private void setListAdapter(ListAdapter adapter) {
// TODO Auto-generated method stub
lv.setAdapter(adapter);
}

android text not visible

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

Categories

Resources