This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
Plz help me
When we get data from server and save in a string variable, it is store in a variable but cantnot retrive.
public class Profile extends Activity {
ListView list;
Activity act;
String[] username = { "Pankaj", "Aaa" };
TextView name;
JSONObject object;
String url = "http://thinksl.com/taughtable/profile.php?user_email=pank#gmail.com";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
list = (ListView) findViewById(R.id.list);
name = (TextView) findViewById(R.id.mailid);
Custom_Profile pro = new Custom_Profile(Profile.this, username);
list.setAdapter(pro);
new Userdata().execute(url);
}
public class Userdata extends AsyncTask<String, Void, String> {
public static final int connection_type = 1500;
Profile p = new Profile();
ProgressDialog dialog;
String resul;
HashMap<String, String> user;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
dialog = new ProgressDialog(Profile.this);
dialog.setTitle("Processing");
dialog.setMessage("Loading Data.Please wait....");
dialog.setCancelable(false);
dialog.show();
}
#Override
protected String doInBackground(String... url) {
// TODO Auto-generated method stub
Log.e("result", "Do in background");
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, connection_type);
HttpConnectionParams.setSoTimeout(params, connection_type);
HttpClient client = new DefaultHttpClient(params);
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("user_email", "pank#gmail.com"));
HttpGet get = new HttpGet(url[0]);
try {
Log.e("result", "Try");
HttpResponse response = client.execute(get);
Log.e("result", "Response" + response);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
Log.e("result", "result" + result);
JSONObject jobject = new JSONObject(result);
object = jobject.getJSONObject("userdetail");
Log.e("result", "result" + object);
String name = object.getString("user_login");
int post = object.getInt("month");
Log.e("name", "name" + name);
Log.e("name", "post" + post);
Log.e("result", "result" + resul);
user = new HashMap<String, String>();
user.put("name", name);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
String s = user.get("name").toString();
p.name.setText(s);
}
}
}
The problem is that you are returning always null, after catch you have the only returning.
Look the last line of doinbackground method, "returning null".
So change to this:
HttpGet get = new HttpGet(url[0]);
HttpResponse response = client.execute(get);
Log.e("result", "Response" + response);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
return result;
And in the postexecute method do it:
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try {
JSONObject jobject = new JSONObject(result);
object = jobject.getJSONObject("userdetail");
Log.e("result", "result" + object);
String name = object.getString("user_login");
int post = object.getInt("month");
Log.e("name", "name" + name);
Log.e("name", "post" + post);
Log.e("result", "result" + resul);
user = new HashMap<String, String>();
user.put("name", name);
dialog.dismiss();
String s = user.get("name").toString();
p.name.setText(s);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
use this code
JSONObject res = new JSONObject(result);
JSONObject response = res.getJSONObject("userdetail");
String niceName = response.getString("user_nicename");
String displayName = response.getString("display_name");
Related
I'm using AsyncTask to insert, update and delete data from database. I used this code to insert, update, delete and it works fine. But when I want to use select, and show the data at EditText, I can't get the value from doInBackground() to the onPostExecute() and it shows nothing.
Here's my code :
MenuUtama.java
public class MenuUtama extends Activity {
/** Called when the activity is first created. */
private TextView nama_user;
private String nm_user = "";
private EditText kode, nama, harga, deskripsi;
private Button insert, update, delete, cek;
private String kode1, nama1, harga1, deskripsi1;
JSONArray data = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
kode = (EditText) findViewById(R.id.editKode);
nama = (EditText) findViewById(R.id.editNama);
harga = (EditText) findViewById(R.id.editHarga);
deskripsi = (EditText) findViewById(R.id.editDes);
cek = (Button) findViewById(R.id.btnCek);
insert = (Button) findViewById(R.id.buttonInsert);
update = (Button) findViewById(R.id.buttonUpdate);
delete = (Button) findViewById(R.id.buttonDelete);
nama_user = (TextView) findViewById(R.id.textView3);
Intent i = getIntent();
nm_user = i.getStringExtra("nama_user");
nama_user.setText(nm_user);
insert.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String url = "";
url = "http://192.168.1.10/crudsederhana/aksi.php";
try {
String ko = URLEncoder.encode(kode.getText().toString(),"utf-8");
String n = URLEncoder.encode(nama.getText().toString(),"utf-8");
String hr = URLEncoder.encode(harga.getText().toString(),"utf-8");
String d = URLEncoder.encode(deskripsi.getText().toString(), "utf-8");
url += "?a=insert&kd=" + ko + "&nm=" + n + "&hrg=" + hr + "&deskripsi=" + d;
new CRUD().execute(url);
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
});
update.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String url = "";
url = "http://192.168.1.10/crudsederhana/aksi.php";
try {
String ko = URLEncoder.encode(kode.getText().toString(),"utf-8");
String n = URLEncoder.encode(nama.getText().toString(),"utf-8");
String hr = URLEncoder.encode(harga.getText().toString(),"utf-8");
String d = URLEncoder.encode(deskripsi.getText().toString(), "utf-8");
url += "?a=update&kd=" + ko + "&nm=" + n + "&hrg=" +hr+ "&des=" + d;
new CRUD().execute(url);
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
});
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String url = "";
kode1 = kode.getText().toString();
url = "http://192.168.1.10/crudsederhana/aksi.php?a=delete&kd=" + kode1;
new CRUD().execute(url);
}
});
cek.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String url = "";
kode1 = kode.getText().toString();
url = "http://192.168.1.10/crudsederhana/aksi.php?a=read&kd="+kode1;
new CRUD().execute(url);
}
});
}
public class CRUD extends AsyncTask<String, String, String> {
String success;
String kode_d, nama_d, harga_d, des_d;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(params[0]);
try {
success = json.getString("success");
Log.e("error", "nilai sukses=" + success);
JSONArray hasil = json.getJSONArray("login");
if (success.equals("1")) {
for (int i = 0; i < hasil.length(); i++) {
JSONObject c = hasil.getJSONObject(i);
kode_d = c.getString("kd");
nama_d = c.getString("nm");
harga_d = c.getString("hrg");
des_d = c.getString("deskripsi");
}
}
else {
Log.e("erro", "tidak bisa ambil data 0");
}
}
catch (Exception e) {
// TODO: handle exception
Log.e("erro", "tidak bisa ambil data 1");
}
return kode_d;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
kode.setText(kode_d);
nama.setText(nama_d);
harga.setText(harga_d);
deskripsi.setText(des_d);
}
}
}
JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
}
catch (Exception e) {
Log.e("Buffer Error", "Error converting result " +e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
}
catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " +e.toString());
}
// return JSON String
return jObj;
}
public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if (method == "POST") {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
else if (method == "GET") {
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
}
catch (Exception e) {
Log.e("Buffer Error", "Error converting result " +e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
}
catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " +e.toString());
}
// return JSON String
return jObj;
}
}
It is because you don't return any value from the doInBackground() (always return null) and you are not using the 'string' in the onPostExecute(String result) formal parameter. Garbage-In-Garbage-Out
your doInBackground() returns just a string return kode_d; and then in your onPostExecute(String result) (which expects a String) you use the kode_d which is null.
If you want all of those values to be returned create an ArrayList(), return it at the end doInBackground() and get it in onPostExecute(ArrayList result) with an iteration and pass it to you textviews.
Even better create an object and add the values to each field. Your fields are the kode_d, nama_d, harga_d, des_d
this is what the onPostExecute does
/**
* <p>Runs on the UI thread after {#link #doInBackground}. The
* specified result is the value returned by {#link #doInBackground}.
* To better support testing frameworks, it is recommended that this be
* written to tolerate direct execution as part of the execute() call.
* The default version does nothing.</p>
*
* <p>This method won't be invoked if the task was cancelled.</p>
*
* #param result The result of the operation computed by {#link #doInBackground}.
*
* #see #onPreExecute
* #see #doInBackground
* #see #onCancelled(Object)
*/
Im working on an Android Application that needed to display a Question(TextView) and Four possible answers(RadioGroup with RadioButtons). Im using a Web Server and MySql for connecting the database into my app. In order to get the data i converted the data into JSON using this method in PHP.
<?php
include_once 'db.php';
class Quiz{
private $db;
private $db_table = "aenglish_questions";
public function __construct(){
$this->db = new DbConnect();
}
public function getAllQuizQuestions(){
$json_array = array();
$query = "select * from aenglish_questions";
$result = mysqli_query($this->db->getDb(), $query);
if(mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_assoc($result)) {
$json_array["quiz_questions"][] = $row;
}
}
return $json_array;
}
}
?>
After getting the JSON data, i needed to display the first question and choices in the textview and radiobuttons in Android studio and when i click the next button it proceeds to the next question.
I`ve try this code and im getting an error message that says my ArrayList is empty.
private class AsyncJsonObject extends AsyncTask<String, Void, String> {
private ProgressDialog progressDialog;
#Override
protected String doInBackground(String... params) {
HttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httpPost = new HttpPost("http://192.168.1.11/LETIA/includes/index.php");
String jsonResult = "";
try {
HttpResponse response = httpClient.execute(httpPost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
System.out.println("Returned Json object " + jsonResult.toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonResult;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = ProgressDialog.show(getActivity(), "Downloading Quiz","Wait....", true);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
System.out.println("Resulted Value: " + result);
parsedObject = returnParsedJsonObject(result);
if(parsedObject == null){
return;
}
quizCount = parsedObject.size();
firstQuestion = parsedObject.get(0);
quizQuestion.setText(firstQuestion.getQuestion());
String[] possibleAnswers = firstQuestion.getAnswers().split(",");
optionOne.setText(possibleAnswers[0]);
optionTwo.setText(possibleAnswers[1]);
optionThree.setText(possibleAnswers[2]);
optionFour.setText(possibleAnswers[3]);
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = br.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return answer;
}
}
I dont know what is the problem and im trying to find an answer for a couple of hours. I just needed it to get pass on my project and any help you provide will have a big impact in my study. Hope you guys can help me.
This is my code on putting the JSON into an ArrayList.
private List<QuizWrapper> returnParsedJsonObject(String result){
List<QuizWrapper> jsonObject = new ArrayList<QuizWrapper>();
JSONObject resultObject = null;
JSONArray jsonArray = null;
QuizWrapper newItemObject = null;
try {
resultObject = new JSONObject(result);
System.out.println("Testing the water " + resultObject.toString());
jsonArray = resultObject.optJSONArray("aenglish_questions");
} catch (JSONException e) {
e.printStackTrace();
}
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jsonChildNode = null;
try {
jsonChildNode = jsonArray.getJSONObject(i);
int id = jsonChildNode.getInt("qae_id");
String question = jsonChildNode.getString("question");
String answerOptions = jsonChildNode.getString("choices");
int correctAnswer = jsonChildNode.getInt("answer");
newItemObject = new QuizWrapper(id, question, answerOptions, correctAnswer);
jsonObject.add(newItemObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonObject;
}
Im having this Error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.pre_boardreviewer, PID: 26290
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:437)
at com.example.recall.EnglishFragments.Question10Fragment$AsyncJsonObject.onPostExecute(Question10Fragment.java:164)
at com.example.recall.EnglishFragments.Question10Fragment$AsyncJsonObject.onPostExecute(Question10Fragment.java:123)
at android.os.AsyncTask.finish(AsyncTask.java:695)
at android.os.AsyncTask.access$600(AsyncTask.java:180)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:712)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7156)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)
I'm trying to program an app to send a String to a service. A friend of mine has a service to receive the data.
Logcat shows this error: "org.json.JSONException: Value FIRST of type java.lang.String cannot be converted to JSONObject"
Here is my code:
Main Activity
public class MainActivity extends Activity {
private String URL = "String with my friend's url";
private Button btnAddValue;
String num = "1";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RadioGroup answer = (RadioGroup) findViewById(R.id.answer);
answer.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
switch (checkedId) {
case R.id.answerA:
num = "1";
break;
case R.id.answerB:
num = "2";
break;
case R.id.answerC:
num = "3";
break;
}
}
});
btnAddValue = (Button) findViewById(R.id.submit);
btnAddValue.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
new AddNewValue().execute(num);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
private class AddNewValue extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(String... arg) {
// TODO Auto-generated method stub
String number = arg[0];
// Preparing post params
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("number", number));
ServiceHandler serviceClient = new ServiceHandler();
String json = serviceClient.makeServiceCall(URL,
ServiceHandler.POST, params);
Log.d("Create Request: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
boolean error = jsonObj.getBoolean("error");
// checking for error node in json
if (!error) {
// new category created successfully
Log.e("Value added successfully ",
"> " + jsonObj.getString("message"));
} else {
Log.e("Add Error: ",
"> " + jsonObj.getString("message"));
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "JSON data error!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
Service Handler
public class ServiceHandler {
static InputStream is = null;
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
response = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error: " + e.toString());
}
return response;
}
}
I read questions to other people with the same problem. The solution seemed to be to add a "{" at the beginning of the json String and a "}" at the end, but it didn't work to me. I tried changing this:
String json = serviceClient.makeServiceCall(URL_NEW_PREDICTION,
ServiceHandler.POST, params);
to this:
String json = "{" + serviceClient.makeServiceCall(URL_NEW_PREDICTION,
ServiceHandler.POST, params) + "}";
but the I got this error:
"org.json.JSONException: Expected ':' after FIRST at character 9 of {FIRST DATA New record created successfully}"
You're receiving back a string that is not able to be parsed to JSON. You can't just make something JSON by adding braces, it needs to adhere to proper JSON formatting. This site shows some good examples of what that means.
Specifically, the parser is telling you that having a space after FIRST isn't okay without having quotes around it...but just adding that won't fix the issue, the problem is more deep than that.
In my main page, I'm calling an AsyncTask that is its own class.
new DownloadFileAsync(context, icon, resultp.get(PublicProfilePage.REVIEWCREATORFBOOKID),"300").execute();
Below is my AsyncTask. I'm reading a JSON trying to get the image's URL. Once I capture that URL I use ImageLoader to cache it, but it does not work.
public class DownloadFileAsync extends AsyncTask<Void, Void, String> {
//private Context context;
CircularImageView bmImage;
ImageLoader imageLoader;
String fbook_id;
String jsonobject;
String image_size;
String size_url;
public DownloadFileAsync(Context context, CircularImageView bmImage, String fbook_id, String size)
{
//this.context = context;
this.bmImage = bmImage;
this.fbook_id = fbook_id;
this.image_size = size;
//Image Loader Initialization
imageLoader = new ImageLoader(context);
if(image_size.equalsIgnoreCase("150")) {
size_url = "https://graph.facebook.com/v2.1/" + fbook_id + "/picture?redirect=0&height=150&width=150";
}else if(image_size.equalsIgnoreCase("300")) {
size_url = "https://graph.facebook.com/v2.1/" + fbook_id + "/picture?redirect=0&height=300&width=300";
}
}
protected String doInBackground(Void... urls) {
String result = null;
String queryResponse = null;
String resultTwo = null;
// Create a new HttpClient and Post Header
HttpClient httpclientBankCheck = new DefaultHttpClient();
HttpGet httppostBankCheck = new HttpGet(size_url);
try {
// Execute HTTP Post Request
HttpResponse responseBankCheck = httpclientBankCheck.execute(httppostBankCheck);
HttpEntity responseText = responseBankCheck.getEntity();
queryResponse = EntityUtils.toString(responseText);
// Retrive JSON Objects from the given website URL in
// JSONfunctions.class
jsonobject = queryResponse;
// Locate the array name
JSONObject arr = new JSONObject(jsonobject);
result = arr.getString("data");
JSONObject arrTwo = new JSONObject(result);
resultTwo = arrTwo.getString("url");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return resultTwo;
}
protected void onPostExecute(String resultTwo) {
//bmImage.setImageBitmap(result);
imageLoader.DisplayImage(resultTwo, bmImage);
}
}
If I hard code the URL into ImageLoader inside my main page, it does work. Is the problem that I'm using an AsyncTask with ImageLoader? It shouldn't be right?
Really appreciate the help!
-M
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.