Android java parsing Json from url to object list - java

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.

Related

FirebaseMessagingService is not getting called in AsyncTask's doInBackground

I have push Notification and I want to update realm objects when the phone gets a notification but when I try launch this:
RealmModelActiveUser actUser= realm.where(RealmModelActiveUser.class).equalTo("id",1).findFirst();
int myid= actUser.getUser().getUser_id();
new ServerBackgroundDownloadConversations(getApplicationContext()) {
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (!result.equals("Error")) {
Log.i("Conversation", "UPDATED");
}
}
}.execute(myid);
The program jumps into the constructor ServerBackgroundDownloadConversations(getApplicationContext()) but doesn't call doInBackground and I don't know why.
My AsyncTask:
public class ServerBackgroundCreateConversation extends AsyncTask<RealmModelConversations,Void,String> {
Context context;
Handler handler;
String out= "";
#SuppressLint("HandlerLeak")
public ServerBackgroundCreateConversation(Context context) {
this.context = context;
handler = new Handler() {
#Override
public void handleMessage(Message msg) {
Bundle bundle= msg.getData();
if (bundle!=null){
out = (String) bundle.get("response");
} else {
out= "Error";
}
}
};
}
#Override
protected String doInBackground(RealmModelConversations... params) {
RealmModelConversations newConv = params[0];
UploadImageApacheHttp uploadTask = new UploadImageApacheHttp();
uploadTask.doFileUpload(newConv.getWork(newConv.getIntWork()), newConv, handler);
while (out.equals("")){
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return out;
}
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(String result) {
if (!result.equals("]") || !result.equals("")){
/// prihlási nového user aj do active (login/register)
CreateNewConversation(result);
} else {
result="Error";
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
private void CreateNewConversation(String result){
Realm realm= Realm.getDefaultInstance();
try {
Gson gson = new Gson();
Type typeConv = new TypeToken<JsonSablonaConversations>() {
}.getType();
JSONObject pom;
JSONArray parentArray = new JSONArray(result);
JSONObject finalObject = parentArray.getJSONObject(0);
JsonSablonaConversations conversation = gson.fromJson(finalObject.toString(), typeConv);
final RealmModelConversations NewUserConv = new RealmModelConversations();
NewUserConv.setId_dialog(conversation.getId_dialog());
NewUserConv.setDate(conversation.getDate());
NewUserConv.setKey(conversation.getKey());
NewUserConv.setId_user(conversation.getId_user());
NewUserConv.setId_user2(conversation.getId_user2());
NewUserConv.setMeno(conversation.getMeno());
NewUserConv.setMeno2(conversation.getMeno2());
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
try {
realm.copyToRealmOrUpdate(NewUserConv);
} catch (Exception e) {
int pom=4;
}
RealmResults<RealmModelConversations> ru= realm.where(RealmModelConversations.class).findAll();
}
});
}
catch (Exception e) {
int ppp=4;
ppp++;
}finally {
realm.close();
}
}
}
I try calling this ↑ from an external thread which is called from a Service, but my AsyncTask has handler and handler needs to be in runOnUIthread and in Thread. I can't get Activity because the thread is called from a Service which doesn't have access to Activity.
I solved my problem with this code
public String postData(int myUserId) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.gallopshop.eu/OFY/getConversations.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id", Integer.toString(myUserId)));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String responseStr = EntityUtils.toString(response.getEntity());
return responseStr;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return null;
}
I will try to put this method & after this method into simply thread, But maybe it's not needed because it's in a service.
Question - Do I put this into Thread or do you think it'll affect the performance of the app?

Nullpointer exception comes in onpostexcute [duplicate]

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");

Image Loader with AsyncTask

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

Fetching PNR status from PNR no. using json [closed]

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.

Reading from textbox when button is pushed in android

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

Categories