How can these two json be different? - java

I am using volley with android. As I am studying this example on github https://github.com/evancharlton/folly . That project made a perfect solution of querying json.
Now comes the problem. If I replace the json url there with another, then the fetching seems not to work!
I know different jsonws need different parsing jobs so I extremely simplified the code. Like this.
public class MainActivity extends SherlockFragmentActivity {
/**
* Called when the activity is first created.
*/
private ViewPager pager;
private PagerSlidingTabStrip tabs;
private MyPagerAdapter adapter;
private String url = "http://konachan.com/post.json?limit=1";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView txt = (TextView) findViewById(R.id.text);
txt.setText("initial");
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
txt.setText("somethinghappend");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
Log.e("wtf", error.toString()) ;
}
});
queue.add(jsObjRequest);
}
}
As you can tell, I removed everything about the content of json but only doing this to figure out why the code goes wrong with only one change: the url
To make it clear:(i dont have enough reputation for multi links so use the comment insdead)
when I set url to
(comment 1)
my TextView successfully change his text(this is the json used in the example project from github, though this is meaningless information since I had built very unrelated code from the example)
but when I switch the address to
(comment 2)
nothing happen to my TextView!(this is the json I really need to work with)
And yes, both jsons are correctly fetched and parsed and displayed in firefox(without any kind of proxy), so I think there are nothing wrong with the jsons and the network.
In fact I think the ONLY difference is that they are different jsons.... with 2 different urls....
Now I seek help from you guys, how can that be? Nothing changed but only a smaller json.. makes everything broken? (is it about timeout matters? but both are loaded very fast in firefox... and obviously the working one contains much more bytes than the not working one...)
the error logged 410 error. The page has Gone?! But it is alive in firefox... and the other json works in both environment(firefox and app)

Related

Force retrofit to load new data

I'm using retrofit to get my json data in my recycleview. It used to work fine couple of weeks ago but I ran code now then It only loads data one time and then as many times as I make change any text or add new value in json data, It always load the same initial data on loading. I haven't used any cache property and strange thing is once it loads first time, then if i delete my json then still it loads the data instead of throwing exception and giving error of json not found.
What am I missing. I changed the version of retrofit but it dosesn't seem to work. Here is my code of Mainactivity is
GetDataService service = RetrofitClientInstance.getRetrofitInstance().create(GetDataService.class);
Call<List<RetroPhoto>> call = service.getAllPhotos();
call.enqueue(new Callback<List<RetroPhoto>>() {
#Override
public void onResponse(Call<List<RetroPhoto>> call, Response<List<RetroPhoto>> response) {
progressDoalog.dismiss();
generateDataList(response.body());
}
#Override
public void onFailure(Call<List<RetroPhoto>> call, Throwable t) {
progressDoalog.dismiss();
Toast.makeText(NewsActivity.this, "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
}
});
}
/*Method to generate List of data using RecyclerView with custom adapter*/
private void generateDataList(List<RetroPhoto> photoList) {
recyclerView = findViewById(R.id.customRecyclerView);
adapter = new CustomAdapter(this,photoList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(NewsActivity.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
and code of GetDataService is
public interface GetDataService {
#GET("b.json")
Call<List<RetroPhoto>> getAllPhotos();
}
and my gradle is
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'com.squareup.okhttp:okhttp:2.4.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.7.0'
compile 'com.jakewharton.picasso:picasso2-okhttp3-downloader:1.1.0'
Thanks in advance for any help. I am banging my heads on floor over 3 hours on figuring out what excatly gone through in couple of weeks where I even didn't touch the code.
I realized problem was from server side as I was using ipage hosing, the i moved json to other hosing and immediately changes were shown in app on request but ipage didn't. So code is fine.

Java android and json - variable confusion

I have an android app that is retrieving data from a mysql db via php.
It works fine, but i have a (simple) variable problem.
I want to create a variable inside MainActivity class.
Then inside MainActiviy class i have onCreate method - and inside that I have some json stuff that retrieves my data from mysql.
I now want to assign some mysql value to the variable i created in MainActivity class (it is assigned inside onResponse method from the json stuff), and then I simply want to use that variable and write it out on a textview, and I will do that in the bottom of the onCreate method.
But for some reason, it "forgets" the value I assigned to the variable, when I have to use it outside the onResponse method.
(if i set the textview text inside the onResponse method, it works fine).
public class MainActivity extends ActionBarActivity {
// I create the variable here
String someString;
TextView text;
RequestQueue reqq;
String showUrl = "http://www.someurl.com/get_data.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.textid);
reqq = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonob = new JsonObjectRequest(Request.Method.POST,
showUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray dataAr = response.getJSONArray("json_data");
for (int i = 0; i < dataAr.length(); i++) {
JSONObject dat = dataAr.getJSONObject(i);
// Here I want to assign some data from my mysql db to the variable
someString = dat.getString("aar");
// If I set the the textview to display value of someString HERE, it works!
// text.setText(someString);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error.getMessage());
}
});
reqq.add(jsonob);
// HERE i want to display the value of the variable in the textview!
// - but it doesnt "remember" the value
text.setText(someString);
}
}
If I use static keyword on the someString variable, it remembers the value, but only the SECOND time i open the app!
I'm very new at this, and have tried google, and tried some stuff with a singleton class, but I just don't seem to understand this!
I would love it, if someone could link me some information to help me get this, AND give an example of how my code should be, so it will work!
THANKS! :D
This behavior is due to the fact that
text.setText(someString);
is executed immediately in the onCreate method, & by immediately I mean that it does not wait for any response from the Volley request (the Volley request that you set up before). In other words, you need to wait till you get a response before you set the text on to your TextView.
That's why it successfully sets your TextView's text from within the onResponse method.

Creating a basic adapter for searchview that uses asynctask

So I'm making this student project Android app that I use to search movies online.
The problem I'm having is that even though there is tons of material to read, I don't quite comprehend how adapters for searchview results are supposed to be made. I know what kind of data the query returns, but I still don't know how to make an adapter for it.
I'm only at a beginner level in Java and Android programming, but this project really fired me up and I've been working on it day and night. If you have any tips (to improve my code) please do share them.
public class SearchActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.searchactivity);
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
new doMySearch().execute(query);
}
}
private class doMySearch extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
String parameters = (params[0]);
JTomato jtomato = new JTomato("gibberish-cencored");
jtomato.setPage_limit(1);
List<Movie> movies = new ArrayList<Movie>();
String total = String.valueOf(jtomato.searchMovie(parameters, movies, 0));
return total;
}
#Override
protected void onPostExecute(String result) {
}
}
}
}
The data this search should return (if the search word were hulk) is as follows: [The Incredible Hulk, Hulk, HULK VS., Hulkamania Forever, Hulk Hogan's All-Time Champ, Hulk Hogan - The Missing Matches] and as many more to be found with that search word. I'm using a Java client for rotten tomatoes API that does most of the coding for me (http requests and json object parsing).
You should probably use the class ArrayAdapter.
You can convert the string you receive into an array of strings, and then create an ArrayAdapter with the list of strings. If you set that adapter as the activity's list adapter, it will show the names of the movies in the activity.

How to modify snippet text of Google Maps v2 Markers in Asynctask?

So, I have searched high and low to find an answer to this problem.
I am trying to figure out how to modify the snippet text of a marker placed on my Google Map (map api v2), in an onPostExecute() call of an asynctask. How I would like to use this in my project, is to update the snippet text once the user has clicked on a marker. Sort of like an update to the information that is pre-set already on that marker.
Example, in order of operation:
User selects a marker on my map,
Asynctask is triggered (through the onMarkerClickListener())
Asynctask preExecute() changes text of snippet to "Fetching next arrival time..."
Asynctask doInBackground() queries my database for the requested data
Asynctask postExecute() sets the selected marker snippet text to "Next: 4:15PM"
I have tried a few different methods, and have arrived at a concise and reasonable solution, but it does not work. The problem I get, is that the marker needs to be of 'final' type, and when I do that, it does not update the snippet text that is displayed to the user, however it still runs through the asynctask and completes successfully.
The following is the code I've tried:
map.setOnMarkerClickListener():
map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
// Update marker next stop time
updateMarkerSnippet(marker);
return false;
}
});
updateMarkerSnippet():
public void updateMarkerSnippet(final Marker marker) {
final String title = marker.getTitle();
AsyncTask<Void, Void, Void> update = new AsyncTask<Void, Void, Void>() {
private String nextArrival = "";
#Override
protected Void onPreExecute() {
marker.setSnippet("Fetching next arrival time...");
}
#Override
protected Void doInBackground(Void... voids) {
nextArrival = db.getNextArrival(title); // db is my database sql class (runs queries)
return null;
}
#Override
protected void onPostExecute(Void result) {
marker.setSnippet("Next: " + nextArrival);
}
};
update.execute((Void[]) null);
}
I just don't want the map to hang while my database is sifting through hundreds of time records. Any help is much appreciated, as I'm sure this would help more than just myself.
This is a known shortcoming in the Android Google Maps API. Take a look here for some workarounds.
it is intresting because marker.setPosition works good but marker.setSnippet does not (for my custom snippet layout), I fixed it like this:
if(marker.isInfoWindowShown())
{
marker.hideInfoWindow();
marker.showInfoWindow();
}

how to retrieve info from datastore using google app engine and display it in a list view on an android app using java?

I am trying to make an android app that retrieves info from google app engine datastore and display it as a listview in the android app..can anyone help me out with some code or explain what exactly needs to be done for this purpose? i have already made modifications on the server side to store data on the datastore..what i dont know is how to get that data onto the android app..i am using eclipse indigo and language is java
EDIT : I am putting my code that i am using to retrieve a set of strings from datastore and put it in a list view...the code is gonna look all haywire but i request you to bear with me and explain how exactly to write it..presently the application is force-closing whenever i get to the page where this list of retrieved strings is supposed to be displayed...
public class Display extends ListActivity
{
private LayoutInflater mInflater;
private Vector<RowData> data;
RowData rd;
static String[] title;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.displaylayout);
MyRequestFactory factory = (MyRequestFactory)Util.getRequestFactory(Display.this,MyRequestFactory.class);
FebfourthRequest febfourthRequest = factory.febfourthRequest();
final List<TrialDBProxy> list= new ArrayList<TrialDBProxy>();
febfourthRequest.queryTrialDBs().fire(new Receiver<List<TrialDBProxy>>()
{
#Override
public void onSuccess(List<TrialDBProxy> arg0) {
// TODO Auto-generated method stub
list.addAll(arg0);
}
});
for(int i=0;i<list.size();i++)
{
title[i] = list.get(i).getMessage();
}
mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
data = new Vector<RowData>();
for(int i=0;i<title.length;i++)
{
rd = new RowData(i,title[i]);
data.add(rd);
}
int[] to = new int[] { R.id.text1, R.id.text2 };
#SuppressWarnings("deprecation")
Cursor mCursor = this.getContentResolver().query(People.CONTENT_URI, null, null, null, null);
ListAdapter adapter = new SimpleCursorAdapter(this,R.layout.displaylayout,mCursor,title,to);
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);
}
private class RowData
{
protected int mId;
protected String mTitle;
RowData(int id,String title)
{
mId=id;
mTitle = title;
}
#Override
public String toString()
{
return mId+" "+mTitle;
}
} '
NOTE : TrialDB is the file that contains all my fields that i want to store on the datastore.
displaylayout is the xml file where i have created a listview.
i am guessing the main part where i have to put code for displaying stuff is in the onCreate() method.
PLEASE HELP !
This is already a very good starting point for learning both Google App Engine and Android Development.
I may write the steps to follow:
Write a Google App Engine application which reads data from datastore and gives as JSON. You can use GAE web framework, or maybe Django. After doing that, you will have a url which gives you your data in your browser.
Write a hello world application for Android. This step gives you an opportunity to understand and setup Android development environment.
Write an Android app which uses a listview with static data.
Extend your Android app with calling a single simple url from web, then print it on your screen.
Extend your application via calling your Google App Engine application url inside your app. Now you have your datastore data in your app.
Populate your listview with your data.

Categories