I'm trying to retrieve the TextBox value when I press the button, but it does not work. Here is my code. Any idea?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.httpxml);
httpstuff = (TextView) findViewById(R.id.http);
client = new DefaultHttpClient();
button = (Button)findViewById(R.id.shoppingprice);
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
//shoppingapi price = new shoppingapi();
et=(EditText)findViewById(R.id.text);
txt=et.getText().toString();
}
});
new Read().execute("displayprice");
}
#SuppressLint("ShowToast")
public JSONObject productprice(String productname) throws ClientProtocolException,IOException,JSONException
{
StringBuilder url = new StringBuilder(URL);
url.append(productname);
url.append("&searchType=keyword&contentType=json");
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
Log.d("Price", "asdasd");
if(status == 200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
jObj = new JSONObject(data);
JSONObject jsonData = jObj.getJSONObject("mercadoresult");
JSONObject jsonProducts = jsonData.getJSONObject("products");
JSONArray jsonArray = jsonProducts.getJSONArray("product");
jsonArray = (JSONArray) jsonArray.get(1);
jObj = (JSONObject)jsonArray.get(0);
return jObj;
}
else
{
Toast.makeText(MainActivity.this,"error",Toast.LENGTH_LONG).show();
return null;
}
}
public class Read extends AsyncTask<String,Integer,String>
{
#Override
protected String doInBackground(String... params) {
try {
json = productprice(txt);
return json.getString("displayprice");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
//super.onPostExecute(result);
//httpstuff.setText("The price of the Product is ");
httpstuff.setText(result);
httpstuff.setText(txt);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
It shows no error but it shows txt value as blank
Because you are calling this line
new Read().execute("displayprice");
in onCreate
Where as txt value is changing when you click on button.
So you are accessing txt value before assigning it. if you want to use the value change like this and try like this
public void onClick(View arg0) {
et=(EditText)findViewById(R.id.text);
txt=et.getText().toString();
new Read().execute("displayprice");
}
});
Reference it outside Button click.
et=(EditText)findViewById(R.id.text);
Access directly inside AsynTask shown below
public class Read extends AsyncTask<String,Integer,String>
{
String txt = et.getText().toString();
#Override
protected String doInBackground(String... params) {
try {
json = productprice(txt);
return json.getString("displayprice");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
//super.onPostExecute(result);
//httpstuff.setText("The price of the Product is ");
httpstuff.setText(result);
httpstuff.setText(txt);
}
}
Related
I am working on an android app development and I am stuck in an issue. I have used ANSYNC TASK method but now it has stopped working.
It was working fine from last many years but now it is creating problem.
Also, doinbackground() and postExecute() methods are not working (they are not called) only preExecute() method is working for me.
I am attaching code here for the reference:
class MyAsyncTask extends AsyncTask<Void, ConversationModel, Void> {
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
heading.setText("myheading");
}
});
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (ConversationModel model : dataList) {
if (flagStop)
break;
publishProgress(model);
long_time = Long.parseLong(model.sound_time) * 1000 + 500;
try {
Thread.sleep(long_time);
Thread.sleep(long_extraTime);
long_extraTime = 0;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
i++;
Log.d("i", i + " -----------------");
}
return null;
}
protected void onProgressUpdate(ConversationModel... model) {
if (i % 2 == 0) {
View v = View.inflate(Conversation1.this, arrInt_resource[0], null);
v.setAnimation(null);
TextView txtV_spn = (TextView) v.findViewById(R.id.textView_spn);
TextView txtV_eng = (TextView) v.findViewById(R.id.textView_eng);
ImageView img_sound = (ImageView) v.findViewById(R.id.imgsound_conv_spn2eng);
RelativeLayout speak_layout = (RelativeLayout) v.findViewById(R.id.speaking_layout);
heading.setText(dataList.get(0).heading);
if (flag != 1) {
txtV_spn.setText(model[0].eng_txt);
txtV_eng.setText(model[0].spn_txt);
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (i >= dataList.size()) {
Log.d("i", i + " ------------------");
makingcontinueImageView();
}
}
}
i think you are using .execute() method of asynctask to start execute of asynctask, change that line of code with this one
asynctask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
I have an App that is receiving a video file from another App that is working as a Server. While the App is saving the file received on the socket, the video stream starts playing the file (which is under construction). In the code sample, after I press the btnStream, I press the btnPlay and App runs successfully. However, if the playing rate is greater than the download rate, an error will occur. I want to avoid this case. So I need to have a listener on the Video Playing that will pause the videoview when it predicts that this error will occur. I know a solution where if I know the video size, I can counter the bytes received and monitor how many seconds have been buffered and see if the videoview should pause or not. However, is it possible to do it without knowing the video file size? Or having two threads that depends on each other? Thanks.
Note: the VideoView used is a custom one where it can play FileDescriptor.
btnStream.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String s = etURL.getText().toString();
String ip = "10.0.0.24";
int port = 7878;
mct= new VideoDownloadTask(ip,port);
mct.execute();
}});
final MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(mVideoView);
Button btnPlay = (Button) findViewById(R.id.button2);
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mVideoView.setVideoFD((new FileInputStream(new File("/sdcard/tempVideo.mp4")).getFD()));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mVideoView.seekTo(0);
mVideoView.start();
}
});
}
public class VideoDownloadTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
Socket socket=null;
VideoDownloadTask(String addr, int port){
dstAddress = addr;
dstPort = port;
}
#Override
protected Void doInBackground(Void... arg0) {
try {
socket = new Socket(InetAddress.getByName(dstAddress), dstPort);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
try {
if(socket!=null)socket.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
File f = new File("/sdcard/tempVideo.mp4");
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DataInputStream in=null;
try {
in = new DataInputStream (socket.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileOutputStream videoFile = null;
try {
videoFile = new FileOutputStream(f);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int len;
byte buffer[] = new byte[8192];
try {
while((len = in.read(buffer)) != -1) {
videoFile.write(buffer, 0, len);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
videoFile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
Toast.makeText(getApplicationContext(), "Done Downloading File",
Toast.LENGTH_LONG).show();
super.onPostExecute(result);
}
}
}
I applied a simple solution that resolved the problem. I am sharing it if anyone is having the same problem. The solution was simply to add an error listener to the videoView that will block the error popups and pauses the video.
mVideoView.setOnErrorListener(new OnErrorListener(){
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
statusText.setText("ERROR PLAYING VIDEO");
mVideoView.pause();
return true;
}
});
pDialog = new ProgressDialog(PlayVideoActivity.this);
pDialog.setTitle("Gajacharitra");
pDialog.setMessage("Buffering video...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
try {
// Start the MediaController
mediacontroller.setAnchorView(mVideoView);
// Get the URL from String VideoURL
Uri video = Uri.parse(mVideoURL);
mVideoView.setMediaController(mediacontroller);
mVideoView.setVideoURI(video);
mVideoView.requestFocus();
mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
// Close the progress bar and play the video
public void onPrepared(MediaPlayer mp) {
pDialog.dismiss();
mVideoView.start();
}
});
mVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
mVideoView.pause();
pDialog.dismiss();
Toast.makeText(PlayVideoActivity.this, "Can't play this video.", Toast.LENGTH_LONG).show();
finish();
return true;
}
});
} catch (Exception e) {
/*Log.e("Error", e.getMessage());
e.printStackTrace();*/
pDialog.dismiss();
Toast.makeText(PlayVideoActivity.this, "Can't play this video.", Toast.LENGTH_LONG).show();
finish();
}
I would like to connect to a Api url, retrieve the json and store everything in a object list. Here is an example of what the url can return as Json.
The following code was given to me but it returns a error Cannot resolve method setOnResponse in my activity line 31
This is my activity.java
public class resultOverview_activity extends Activity implements onResponse{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_overview);
Bundle search_activity_data = getIntent().getExtras();
if(search_activity_data == null){
return;
}
String URL = "http://www.gw2spidy.com/api/v0.9/json/item-search/Sunrise";
AsyncTask parkingInfoFetch = new AsyncFetch(this);
parkingInfoFetch.setOnResponse(this);
parkingInfoFetch.execute(URL);
//Log.i("gw2Log", parkingInfoFetch.);
}
#Override
public void onResponse(JSONObject object) {
Log.d("Json Response", "Json Response" + object);
ResultClass resultClass = new ResultClass();
try {
resultClass.setCount(object.getInt("count"));
resultClass.setPage(object.getInt("page"));
resultClass.setLast_page(object.getInt("last_page"));
resultClass.setTotal(object.getInt("total"));
JSONArray array = new JSONArray(object.getString("results"));
for (int i = 0; i < resultClass.getTotal(); i++) {
JSONObject resultsObject = array.getJSONObject(i);
resultClass.setData_id(resultsObject.getInt("data_id"));
resultClass.setName(resultsObject.getString("name"));
resultClass.setRarity(resultsObject.getInt("rarity"));
resultClass.setRestriction_level(resultsObject
.getInt("restriction_level"));
resultClass.setImg(resultsObject.getString("img"));
resultClass.setType_id(resultsObject.getInt("type_id"));
resultClass.setSub_type_id(resultsObject.getInt("sub_type_id"));
resultClass.setPrice_last_changed(resultsObject
.getString("price_last_changed"));
resultClass.setMax_offer_unit_price(resultsObject
.getInt("max_offer_unit_price"));
resultClass.setMin_sale_unit_price(resultsObject
.getInt("min_sale_unit_price"));
resultClass.setOffer_availability(resultsObject
.getInt("offer_availability"));
resultClass.setSale_availability(resultsObject
.getInt("sale_availability"));
resultClass.setSale_price_change_last_hour(resultsObject
.getInt("sale_price_change_last_hour"));
resultClass.setOffer_price_change_last_hour(resultsObject
.getInt("offer_price_change_last_hour"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
AsyncFetch.java class
public class AsyncFetch extends AsyncTask<String, Void, JSONObject> {
public AsyncFetch(Context context) {
this.context = context;
}
private Context context;
private JSONObject jsonObject;
private onResponse onResponse;
public onResponse getOnResponse() {
return onResponse;
}
public void setOnResponse(onResponse onResponse) {
this.onResponse = onResponse;
}
#Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
try {
HttpGet get = new HttpGet(params[0]);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
jsonObject = new JSONObject(result);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonObject;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
this.onResponse.onResponse(result);
}
public interface onResponse {
public void onResponse(JSONObject object);
}
}
And ofcourse the constructur ResultClass which i assume is not necessary to include here as code.
What does this error Cannot resolve method setOnResponse mean and how do i fix this?
Change this line:
AsyncTask parkingInfoFetch = new AsyncFetch(this);
To this:
AsyncFetch parkingInfoFetch = new AsyncFetch(this);
The error means that the line:
parkingInfoFetch.setOnResponse(this);
Is trying to call a method defined in the subclass AsyncFetch, but you have the variable defined as the parent class AsyncTask which has no method setOnResponse.
I am doing a validation for fields in an android form.I am checking with server whether the username is available in the server or not.But the main thread goes to the next page before the async checking completes.
The code:
btnnext1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
isallValid=true;
//check second time for username validation(first time was in onfocus changed)
// if(txtusername.getText().toString().trim().equals("achuthan")){
// txtusername.setError("Username exsists!");
// isUsernameValid=false;
// }
//
// else
// {
// isUsernameValid=true;
// }
try {
Void async_result=new validateusername().execute().get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(txtfullname.getText().toString().trim().length()==0)
{
txtfullname.requestFocus();
txtfullname.setError("Field required");
isallValid=false;
}
if(txtdob.getText().toString().trim().length()==0)
{
txtdob.requestFocus();
txtdob.setError("Field required");
isallValid=false;
}
if(txtoccupation.getText().toString().trim().length()==0)
{
txtoccupation.requestFocus();
txtoccupation.setError("Field required");
isallValid=false;
}
if(txtusername.getText().toString().trim().length()<6){
txtusername.requestFocus();
txtusername.setError("Minimum length of 6 characters");
isallValid=false;
}
if(txtpassword.getText().toString().trim().length()==0)
{
txtpassword.requestFocus();
txtpassword.setError("Field required");
isallValid=false;
}
if(txtconfirmpassword.getText().toString().trim().length()==0)
{
txtconfirmpassword.requestFocus();
txtconfirmpassword.setError("Field required");
isallValid=false;
}
else if(!txtpassword.getText().toString().trim().equals(txtconfirmpassword.getText().toString().trim()))
{
//txtconfirmpassword.requestFocus();
txtconfirmpassword.setError("Passwords not equal");
txtpassword.setError("Passwords not equal");
isallValid=false;
}
if(isallValid&&isUsernameValid)
{
//Toast.makeText(getActivity(),"VALID FORM!!",Toast.LENGTH_LONG).show();
((SignUpPage)getActivity()).getValues().fullname=txtfullname.getText().toString().trim();
((SignUpPage)getActivity()).getValues().dob=txtdob.getText().toString().trim();
int id=radiogender.getCheckedRadioButtonId();
RadioButton rb=(RadioButton) view.findViewById(id);
String gender=rb.getText().toString();
((SignUpPage)getActivity()).getValues().gender=gender;
int id1=radiomarital.getCheckedRadioButtonId();
RadioButton rb1=(RadioButton) view.findViewById(id1);
String marital_status=rb1.getText().toString();
((SignUpPage)getActivity()).getValues().marital_status=marital_status;
((SignUpPage)getActivity()).getValues().occupation=txtoccupation.getText().toString().trim();
((SignUpPage)getActivity()).getValues().username=txtusername.getText().toString().trim();
((SignUpPage)getActivity()).getValues().password=txtpassword.getText().toString().trim();
((SignUpPage)getActivity()).selectFragment(1);
}
//if all valid , store values and go to next fragment
//((SignUpPage)getActivity()).selectFragment(1);
}
});
return view;
}
The async class:
public class validateusername extends AsyncTask<String,Void,Void>
{
#Override
protected Void doInBackground(String... arg0) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("username",txtusername.getText().toString().trim()));
try {
httppost.setEntity(new UrlEncodedFormEntity(pairs));
response = httpclient.execute(httppost);
result=responsetostring.getResponseBody(response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result1) {
try {
jsonobj=new JSONObject(result);
job2=jsonobj.getJSONObject("server_message");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
finalresult=job2.getString("username_availability_message");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(finalresult.equals("exist")){
txtusername.setError("Username exsists!");
isUsernameValid=false;
}
else if(finalresult.equals("available"))
{
isUsernameValid=true;
}
}
}
I tried using the get method so that the main thread waits till the async class finishes but it didnt work.Please help!!
Check isallValid only in button click , then Do this validation inside your onPostExecute(Void result) method,
if(isUsernameValid)
{
//Toast.makeText(getActivity(),"VALID FORM!!",Toast.LENGTH_LONG).show();
((SignUpPage)getActivity()).getValues().fullname=txtfullname.getText().toString().trim();
((SignUpPage)getActivity()).getValues().dob=txtdob.getText().toString().trim();
int id=radiogender.getCheckedRadioButtonId();
RadioButton rb=(RadioButton) view.findViewById(id);
String gender=rb.getText().toString();
((SignUpPage)getActivity()).getValues().gender=gender;
int id1=radiomarital.getCheckedRadioButtonId();
RadioButton rb1=(RadioButton) view.findViewById(id1);
String marital_status=rb1.getText().toString();
((SignUpPage)getActivity()).getValues().marital_status=marital_status;
((SignUpPage)getActivity()).getValues().occupation=txtoccupation.getText().toString().trim();
((SignUpPage)getActivity()).getValues().username=txtusername.getText().toString().trim();
((SignUpPage)getActivity()).getValues().password=txtpassword.getText().toString().trim();
((SignUpPage)getActivity()).selectFragment(1);
}
now it will work.................
Do not use get() to call the AsyncTask, it hangs your UI.
So call your AsyncTask like,
String userName = txtusername.getText().toString().trim();
new validateusername().execute(userName); // pass the String from EditText, as you cannot interact with UI in doInBackground
Modify your AsyncTask like
public class validateusername extends AsyncTask<String,Void,String>
{
#Override
protected String doInBackground(String... arg0) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("username",arg0[0])); // arg0[0] is the username passed from AsyncTask call
try {
httppost.setEntity(new UrlEncodedFormEntity(pairs));
response = httpclient.execute(httppost);
result=responsetostring.getResponseBody(response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result1) {
try {
jsonobj=new JSONObject(result);
job2=jsonobj.getJSONObject("server_message");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
finalresult=job2.getString("username_availability_message");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(finalresult.equals("exist")){
txtusername.setError("Username exsists!");
isUsernameValid=false;
}
else if(finalresult.equals("available"))
{
isUsernameValid=true;
}
if(txtfullname.getText().toString().trim().length()==0)
{
txtfullname.requestFocus();
txtfullname.setError("Field required");
isallValid=false;
}
if(txtdob.getText().toString().trim().length()==0)
{
txtdob.requestFocus();
txtdob.setError("Field required");
isallValid=false;
}
if(txtoccupation.getText().toString().trim().length()==0)
{
txtoccupation.requestFocus();
txtoccupation.setError("Field required");
isallValid=false;
}
if(txtusername.getText().toString().trim().length()<6){
txtusername.requestFocus();
txtusername.setError("Minimum length of 6 characters");
isallValid=false;
}
if(txtpassword.getText().toString().trim().length()==0)
{
txtpassword.requestFocus();
txtpassword.setError("Field required");
isallValid=false;
}
if(txtconfirmpassword.getText().toString().trim().length()==0)
{
txtconfirmpassword.requestFocus();
txtconfirmpassword.setError("Field required");
isallValid=false;
}
else if(!txtpassword.getText().toString().trim().equals(txtconfirmpassword.getText().toString().trim()))
{
//txtconfirmpassword.requestFocus();
txtconfirmpassword.setError("Passwords not equal");
txtpassword.setError("Passwords not equal");
isallValid=false;
}
if(isallValid&&isUsernameValid)
{
//Toast.makeText(getActivity(),"VALID FORM!!",Toast.LENGTH_LONG).show();
((SignUpPage)getActivity()).getValues().fullname=txtfullname.getText().toString().trim();
((SignUpPage)getActivity()).getValues().dob=txtdob.getText().toString().trim();
int id=radiogender.getCheckedRadioButtonId();
RadioButton rb=(RadioButton) view.findViewById(id);
String gender=rb.getText().toString();
((SignUpPage)getActivity()).getValues().gender=gender;
int id1=radiomarital.getCheckedRadioButtonId();
RadioButton rb1=(RadioButton) view.findViewById(id1);
String marital_status=rb1.getText().toString();
((SignUpPage)getActivity()).getValues().marital_status=marital_status;
((SignUpPage)getActivity()).getValues().occupation=txtoccupation.getText().toString().trim();
((SignUpPage)getActivity()).getValues().username=txtusername.getText().toString().trim();
((SignUpPage)getActivity()).getValues().password=txtpassword.getText().toString().trim();
((SignUpPage)getActivity()).selectFragment(1);
}
}
onPostExecute(), check the conditions and navigate to next activity.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am android beginner and trying to fetch pnr status using json here is my code which is not working please help me .
Also tell me which parsing method is goo xml parse or json parse.
When you asking questions, using some more words to describe your problem will always help. If there are really nothing more to say, just copy some random paragraph from internet, but make sure you mark them as dummy text so that people won't pay attention on them.
public class JSON extends Activity {
String completeData="";
TextView tv;
EditText et;
Button bt;
HttpClient client;
JSONObject jsonobj;
final static String URI="http://pnrapi.alagu.net/api/v1.0/pnr/";
String pnr_no=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_json);
tv=(TextView) findViewById(R.id.textView1);
et=(EditText) findViewById(R.id.editText1);
bt=(Button) findViewById(R.id.button1);
client=new DefaultHttpClient();
}
public void showpnr(View v){
pnr_no=et.getText().toString();
if(pnr_no.equals("")){
Toast.makeText(this, "Enter the Valid Pnr", Toast.LENGTH_LONG).show();
return;
}
GetPNR pnr=new GetPNR();
pnr.execute("train-name");
completeData="";
}
public JSONArray pnr(String username){
JSONArray jarray=null;
try
{
StringBuilder builder=new StringBuilder(URI);
builder.append(username);
HttpGet get=new HttpGet(builder.toString());
HttpResponse response=client.execute(get);
int status =response.getStatusLine().getStatusCode();
if(status==200){
HttpEntity entity=response.getEntity();
String data=EntityUtils.toString(entity);
jarray=new JSONArray(data);
}
else{
Toast.makeText(this, "Error", Toast.LENGTH_LONG).show();
}
}catch(ClientProtocolException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
catch(JSONException e){
e.printStackTrace();
}
catch(Exception e){
e.printStackTrace();
}
return jarray;
}
JSONObject js_pnr=new JSONObject();
public class GetPNR extends AsyncTask<String, Integer, ArrayList<String>>
{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
tv.setText("Loading Pnr status");
super.onPreExecute();
}
#Override
protected ArrayList<String> doInBackground(String... params) {
// TODO Auto-generated method stub
ArrayList<String> al_texts=new ArrayList<String>();
try{
JSONArray data =pnr(pnr_no);
if(data==null){
return null;
}
int count=data.length();
JSONObject jobj=new JSONObject();
for(int i=0;i<count;i++){
jobj=data.getJSONObject(i);
al_texts.add(jobj.getString("train-name").toString());
}
return al_texts;
}catch(JSONException e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(ArrayList<String> al_pnrText) {
if(al_pnrText==null){
tv.setText("Pnr not found");
return;
}
for(String string:al_pnrText){
completeData+=string+System.getProperty("line.seperator")
+System.getProperty("line.seperator");
}
tv.setText("pnr status:"+System.getProperty("line.seperator")+completeData);
}
}
}
Inside your button onclick just write:
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String details = "";
GetPNR pnrDetails = new GetPNR();
try {
details = pnrDetails.execute(URI+et.getText().toString()).get();
Log.d("train", details);
tv.setText(details);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
And the Asynctask is like:
public class GetPNR extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String al_texts = "";
for(String newUrl:params){
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(newUrl);
HttpResponse response;
try {
response = client.execute(get);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String webData = "";
while((webData = reader.readLine()) != null){
Log.i("data", webData);
JSONObject myAwway = new JSONObject(webData);
JSONObject data = myAwway.getJSONObject("data");
Log.i("data", data.toString());
JSONObject travelDate = data.getJSONObject("travel_date");
JSONObject from = data.getJSONObject("from");
JSONObject to = data.getJSONObject("to");
JSONObject alright = data.getJSONObject("alight");
JSONObject board = data.getJSONObject("board");
JSONArray passenger = data.getJSONArray("passenger");
al_texts = data.getString("train_name");
Log.i("data", al_texts);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return al_texts;
}
}
here I'm showing/returning only a string(train name).Like this you can show every details .
this is your modified code and working fine.