Getting data from Server too slow ? (Android) - android

I am trying to populate RecyclerView by the list of transactions i get from the server . but unless i put a Thread.sleep(7000) , it won't populate .
Does it take this much time to get data from server side ? If yes , Is there any faster alternative ?
or is getting the string from json response and adding object to list is time consuming ? because this sleep is just working for adding 5 rows in list. when i try to run loop for whole number of rows i don't get any data .
My host is PythonAnywhere .
API response is in json and has around 400 records :
http://sairav.pythonanywhere.com/getTransaction
Using :
Android Asynchronous Http Client:::
compile 'com.loopj.android:android-async-http:1.4.9'
public List<Transaction> getTransactions(final boolean getAll) {
Thread bgThread =null;
final List<Transaction> trList=new ArrayList<>();
RequestParams requestParams = new RequestParams();
requestParams.put("uid", Profile.getCurrentProfile().getId());
PAAPI.post("/getTransaction", requestParams, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray jsonArray) {
Transaction trr = null;
if (getAll) {
for (int i = 0; i < 5; i++) {
try {
//String a = jsonArray.getString(i);
JSONObject jsonObject = jsonArray.getJSONObject(i);
//JSONArray arrayWithElements = jsonObject.toJSONArray(new JSONArray(new String[]{"name","desc","amount","ttype","uid","ttime"}));
trr = new Transaction(context);
trr.uname = jsonObject.getString("uname");
trr.desc = jsonObject.getString("description");
trr.amount = jsonObject.getString("amount");
trr.type = jsonObject.getString("type");
trr.uid = jsonObject.getString("uid");
trr.date = jsonObject.getString("ttime");
trList.add(trr);
// Toast.makeText(context,"size is bro :"+trList.size(),Toast.LENGTH_SHORT).show();
if (i == 1) {
// Toast.makeText(context, trr.uname + "-" + desc + "-" + trr.amount + "-" + trr.type + "-" + trr.uid + "-" + trr.date, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// Do something with the response
}
});
try {
Toast.makeText(context,"sleeping bo",Toast.LENGTH_SHORT).show();
Thread.sleep(7000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Toast.makeText(context, "listsize final is" + trList.size(), Toast.LENGTH_SHORT).show();
return trList;
}
class PAAPI {
protected static final String BASE_URL = "http://sairav.pythonanywhere.com";
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
}
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return BASE_URL + relativeUrl;
}
}

If you are certain that getString() operation is taking too much time to perform then you can use progress dialog instead of using Thread.sleep()
private class PAAPI extends AsyncTask<Boolean, Void, List<Transaction> {
ProgressDialog dialog = new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute() {
//set message of the dialog
dialog.setMessage("Loading...");
//show dialog
dialog.show();
super.onPreExecute();
}
protected Void doInBackground(Boolean... args) {
// do background work here
return null;
}
protected void onPostExecute(List<Transaction> result) {
// do UI work here
if(dialog != null && dialog.isShowing()){
dialog.dismiss()
}
}
}
and later use it as new PAAPI().execute(getAll);

Use the retrofit library available to retrieve or post the data from a JSON URL ...it is very easy to use and is efficient

Related

Simplest straight forward way to get a JSON String from a REST URL

I am trying to get a JSON string from a url and save it into SQLite in my android app.
I was trying some tutorials then realize the suggested methods has a void return type. Are there a more simple straight forward way of getting a JSON String and putting it into an arraylist ready to be saved into SQLite?
Below is what I was stuck at a helper class that gets the data from the url
as they said that the main thread OnCreate does not allow a background process like this. Is there a way to change the return type of AsyncTask or is there a more simple way to fetch JSON String with android?
public class FetchData extends AsyncTask<Void, Void, Void> {
#Override
protected void doInBackground(ArrayList<String>... voids) {
try {
URL url = new URL("http://192.168.403.211/api/wordsupdate.php");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader (new InputStreamReader(inputStream));
String line ="";
while (line != null) {
line = bufferedReader.readLine();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Go with Volley API. Check the code below which demonstrate POST request. Hope you'll get useful information.
public void getAddress(final String uid) {
String url = "Add Url Here"; // Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONArray dataArray;
JSONObject jsonObject;
address_ids = new ArrayList<>();
address_names = new ArrayList<>();
address_line1 = new ArrayList<>();
address_line2 = new ArrayList<>();
address_state = new ArrayList<>();
address_district = new ArrayList<>();
address_taluka = new ArrayList<>();
address_pincode = new ArrayList<>();
address_status = new ArrayList<>();
address_default = new ArrayList<>();
try {
jsonObject = new JSONObject(response);
dataArray = jsonObject.getJSONArray(JSON_ARRAY);
//adding response values to respective array
for (int i = 0; i < dataArray.length(); i++) {
//Creating a json object of the current index
JSONObject obj;
try {
//getting json object from current index
obj = dataArray.getJSONObject(i);
address_ids.add(obj.getString(TAG_ADDRESS_ID));
address_names.add(obj.getString(TAG_ADDRESS_NAME));
address_line1.add(obj.getString(TAG_ADDRESSLINE_FIRST));
address_line2.add(obj.getString(TAG_ADDRESSLINE_SECOND));
address_state.add(obj.getString(TAG_STATE));
address_district.add(obj.getString(TAG_DISTRICT));
address_taluka.add(obj.getString(TAG_TALUKA));
address_pincode.add(obj.getString(TAG_PINCODE));
address_status.add(obj.getString(TAG_ADDRESS_STATUS));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
//setting up response values to the fragment
//Toast.makeText(getActivity(), "Error:"+response, Toast.LENGTH_LONG).show();
Log.e(TAG, "onResponse: " + response);
address_name.setText("Name : " + address_names.get(0));
address.setText("Address : " + address_line1.get(0) + "," + address_line2.get(0) + "-" + address_pincode.get(0));
taluka.setText("Taluka : " + address_taluka.get(0));
district.setText("District : " + address_district.get(0));
state.setText("State : " + address_state.get(0));
mCircularProgressBar.setIndeterminate(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplication(), "Taking bit longer", Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("mk_address_id", address_id);
return params;
}
};
queue.add(stringRequest);
}
Check this link from Android developer, you can find more info their.
In your code change the "extends" from
AsyncTask<Void, Void, Void>
to
AsyncTask<Void, Void, String>
and the doInBackground method to
protected String doInBackground(ArrayList<String>... voids)
and you will get the string back in the onPostExecute method
Yes there is a way to change the return types: Have a look at your extends AsyncTask: It says AsyncTask<Void, Void, Void>.
According to Android Developers, this means <Params, Progress, Result>.
This means that your
ArrayList<String>... voids won't work too, because you have the Params part set to Void but try to get an ArrayList<String>.
So, to solve your problem, change the three Voids to whatever you need it to input and output.
However, to deserialize JSON you should use an external library (or use a 3rd party library for REST calls altogether).
//AsyncTask has onPostExecute which will be called after background execution, where you will get the result in mainthread
class FetchData extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL("http://192.168.403.211/api/wordsupdate.php");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
//Your result String is here which runs on MAIN THREAD
super.onPostExecute(result);
}
}
Retrofit 2 will help you - easy and simple
Edit : For Async task see the top answer here
What arguments are passed into AsyncTask<arg1, arg2, arg3>?
In your code snippet , you specified AsyncTask params types are Void. Void means , it does't have any return value. As per AsyncTask Syntax,
You have to specify three arguments.
1- InputType- DoInBanckground
2- ProgressType - Publish Progress.
3- OutputType - OnPostExecute.
The three types used by an asynchronous task are the following:
Params, the type of the parameters sent to the task upon execution.
Progress, the type of the progress units published during the background computation.
Result, the type of the result of the background computation.
In your snippet doInBackground method and AsycTask types are mismatching .
For more information : https://developer.android.com/reference/android/os/AsyncTask.html

how to fetch result from asynctask into mainactivity

I am trying to make a translater app and all code is working fine but at the last part my app is crashed while fetching the result from asynctask into mainactivity,what I'm doing wrong here
enter code here
MainActivity.java
b.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View p1)
{
// TODO: Implement this method
texttotranslate = et.getText().toString();
Log.d("text:", "" + texttotranslate);
OkhttpHandler myTask = new OkhttpHandler(new AsyncResponse(){
#Override
public void processFinish(String output)
{
// TODO: Implement this method
Log.d("Response from asynctask", (String) output);
t.setText((String)output);
}
});
myTask.execute(texttotranslate, lang_pair);
}
});
I already created an interface AsyncResponse and added a method processFinish(String output) into it
enter code here
OkHttpHandler.java
public class OkhttpHandler extends AsyncTask<String,Void,String>
{
String res;
String transres;
String finalres;
public AsyncResponse delegate;
public OkhttpHandler(AsyncResponse delegate)
{
this.delegate = delegate;
}
#Override
protected String doInBackground(String[] values)
{
// TODO: Implement this method
OkHttpClient client = new OkHttpClient();
String texttotranslate = values[0];
String lang_pair = values[1];
String key = "my-key";
String url = "https://translate.yandex.net/api/v1.5/tr.json/translate?key=" + key
+ "&text=" + texttotranslate + "&lang=" + lang_pair;
Request request = new Request.Builder().url(url).build();
try
{
Response response = client.newCall(request).execute();
res = response.body().string();
}
catch (IOException e)
{
e.printStackTrace();
}
if (res != null)
{
try
{
JSONObject jsonobj = new JSONObject(res);
transres = jsonobj.getString("text");
String f = transres.replace("[", "");
String s = f.replace("]", "");
finalres = s.replace("\"", "");
Log.d("final result", "" + finalres);
}
catch (JSONException e)
{
e.printStackTrace();
}
}
return finalres;
}
#Override
protected void onPostExecute(String result)
{
// TODO: Implement this method
super.onPostExecute(result);
delegate.processFinish(result);
Log.d("result:", "" + result);
}
}
My app is crashed while launching and there is no any error showing in my logcat.
You should replace my-key with your yandex API_KEY
String key = "my-key";
Everything else is fine I tried your code
https://github.com/naveendew/yandex_translate_example
I had accidentally deleted okio library from libs folder that's why my app was crashing, so now it's solved.
So if anyone using okhttp library then add okio library too.

Running Async in a fragment is not even being ran

I am running the commands like so:
new GetGameScoresFromFuhantikAPI()
And my method for this is ->
private class GetGameScoresFromFuhantikAPI extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
MethodContants.showLog(TAG, "Loading FUHNATIK API", true);
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = API_URL + jsonFile;
// String url = "http://www.nfl.com/liveupdate/game-center/" + list.get(i) + "/" + list.get(i) + "_gtd.json";
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from FUHNATIK API: " + url);
if (jsonStr != null) {
try {
//JSONObject object = new JSONObject(json);
JSONObject object = new JSONObject(jsonStr);
currentWeek = object.getString("pypwk");
currentWeekDB = object.getString("mdb");
JSONArray array = (JSONArray) object.get("g");
scheduleModelList = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
//TODO IF WE DONT PLAY THURSDAY GAMES PUT LIST.ADD IN HERE
// if (!array.getJSONObject(i).getString("-d").equals("Thu")){
//
// }
scheduleModelList.add(new ScheduleModel(array.getJSONObject(i).getString("-v"),
array.getJSONObject(i).getString("-h"),
array.getJSONObject(i).getString("-t"),
array.getJSONObject(i).getString("-d"),
array.getJSONObject(i).getString("-eid").substring(0, 8),
array.getJSONObject(i).getString("-t") + array.getJSONObject(i).getString("-q"),
array.getJSONObject(i).getString("-vnn"),
array.getJSONObject(i).getString("-hnn"),
"...select a team...",
array.getJSONObject(i).getString("-eid"),
array.getJSONObject(i).getString("-vs"),
array.getJSONObject(i).getString("-hs"),
array.getJSONObject(i).getString("-w")));
}
} catch (final JSONException e) {
Log.e(TAG, "FUHNATIK API: Json parsing error: " + e.getMessage());
}
} else {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Log.e(TAG, "FUHNATIK API: Couldn't get json from server.");
Toast.makeText(getContext(), "Getting from ESPN", Toast.LENGTH_SHORT).show();
//new GetGameScoresFromESPN().execute();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
final ListViewAdapterResults adapter = new ListViewAdapterResults(listView.getContext(), scheduleModelList);
listView.setAdapter(adapter);
MethodContants.showLog(TAG, "DONE WITH LOADING FUHNATIK API", false);
}
}
I can't seem to figure out why the code never get ran. I ran through the debugger but I really can't pinpoint where this is failing out. Any help on this would be appreciated.
Eventually if the json file is not at this URL, I will be getting the json from NFL. However, Without this working, the ESPN won't work either, and I really can not figure out where the error is on my end. I have to assume this will be a pretty easy fix.
Again, as said before, any help would be very appreciated!!
In the above line of code you call the Class but you forgot to execute your asynctask. So no Overriden methods are called. Try this:
new GetGameScoresFromFuhantikAPI().execute();
If you want to pass something as argument, give parameters separated by coma like this:
new GetGameScoresFromFuhantikAPI().execute(arg0, arg1);

Get JSON response in listview and how to show it in listview?

I am a beginner in Android. I want to get a JSON response in a list and show it in a ListView . How to do this?
Here is my code for JSON post.
public class NewTest extends AppCompatActivity { TextView
txtJson;
Button btnOkay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_test);
txtJson= (TextView) findViewById(R.id.txtJson);
assert (findViewById(R.id.btnOkay)) != null;
(findViewById(R.id.btnOkay)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { new TaskPostWebService("written url here").execute(((TextView)
findViewById(R.id.txtJson)).getText().toString());
}
}); }
private class TaskPostWebService extends AsyncTask<String,Void,String> {
private String url;
private ProgressDialog progressDialog;
private JSONParser jsonParser;
public TaskPostWebService(String url ){
this.url = url;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(NewTest.this,"","");
}
#Override
protected String doInBackground(String... params) {
String fact = "";
try {
final MediaType JSON = MediaType.parse("application/json");
android.util.Log.e("charset", "charset - " + JSON.charset());
OkHttpClient client = new OkHttpClient();
//Create a JSONObject with the data to be sent to the server
final JSONObject dataToSend = new JSONObject()
.put("nonce", "G9Ivek")
.put("iUserId", "477");
android.util.Log.e("data - ", "data - " + dataToSend.toString());
//Create request object
Request request = new Request.Builder()
.url("written url here")
.post(RequestBody.create(JSON, dataToSend.toString().getBytes(Charset.forName("UTF-8"))))
.addHeader("Content-Type", "application/json")
.build();
android.util.Log.e("request - ", "request - " + request.toString());
android.util.Log.e("headers - ", "headers - " + request.headers().toString());
android.util.Log.e("body - ", "body - " + request.body().toString());
//Make the request
Response response = client.newCall(request).execute();
android.util.Log.e("response", " " + response.body().string()); //Convert the response to String
String responseData = response.body().string();
//Construct JSONObject of the response string
JSONObject dataReceived = new JSONObject(responseData);
//See the response from the server
Log.i("response data", dataReceived.toString());
}
catch (Exception e){
e.printStackTrace();
}
return fact;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
TextView text = (TextView) findViewById(R.id.txtJson);
text.setText(s);
progressDialog.dismiss();
}
}
So, how can I get a response in a list and show it in a ListView?
Welcome to stackOverflow,
as you are beginner so before going to complete solutions, you can think and follow following steps.
1.Network request:
For network request, we have lib volley(by Google) and retrofit(by Square). You can use this for network request and response.
2.JSON Parsing: You can used eigther GSON lib or using JSONObject/ jsonArray to parse json data. I'll recommend you to write your own parsing code for better understanding of JSON parsing.
3.ListView data binding: At this step, you should have parsed data in list(other data structure can be used to store data also). Create Adapter and bind listview with adapters.
I have not provided solutions for this, you should implement yourself and let me know for any doubts. Hope this should work.
ArrayList<JSONObject> arrayListJson;
ArrayList<String> arrayList;
ArrayAdapter<String> adapter;
ListView listView = (ListView) fragmentView.findViewById(R.id.listView);
adapter = new ArrayAdapter<> (getActivity(), android.R.layout.simple_list_item_1, arrayList);
listView.setAdapter(adapter);
now in a separate thread:
JSONObject jResponse = new JSONObject(responseStr);
JSONArray jArray= jResponse.getJSONArray("OUTER_KEY");
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
arrayList.add(jsonObject.optString("INNER_KEY"));
arrayListJson.add(jsonObject);
}
adapter.notifyDataSetChanged();

JSON from php file to java array

I know that there are a few question about this subject, but I read them and I tried the soluttion but it didn't work :(
the PHP script give this json array result: data[x] =
["alon","62","1.82","22","0","70","0","1"]
(this is the data[x] variable)
I have to convert this result to Java variabls like name,weight,height etc.. but I don't know how..
please help me
my function:
private class LongOperation extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Error = null;
protected void onPreExecute() {
}
protected Void doInBackground(String... urls) {
try {
HttpGet httpget = new HttpGet(urls[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
data[x] = Client.execute(httpget, responseHandler);
} catch (ClientProtocolException e) {
Error = e.getMessage();
Toast.makeText(getApplicationContext(),"error2" , Toast.LENGTH_LONG).show();
cancel(true);
} catch (IOException e) {
Error = e.getMessage();
Toast.makeText(getApplicationContext(),"error34" , Toast.LENGTH_LONG).show();
cancel(true);
}
return null;
}
public void onPostExecute(Void unused) {
String name = null,weight = null;
if (Error != null) {
} else {
// here I have to do something with the arrays...
Toast.makeText(getApplicationContext(),"d:" + data[x] + "o:" + name + " : " + weight, Toast.LENGTH_LONG).show();
}
x++;
}
}
Create a Modal Class for that.
class myModal {
private String name, weight, height, ...;
public String getName() { return this.name; }
public void setName(String name) { this.name = name; }
//and more getters and setters
}
JSONObject json = new JSONObject(data[x]); // in your sample its a JSONArray but its wrong formatted. make sure you encode it properply with php json_encode(array("data", yourdata))...);
myModal modal = new myModal();
modal.setName(json.getString("name"));
php should be something like
<?php
$data = array("name" => "myname", "weight" => 20);
print json_encode( $data );
?>
while the json can be parsed in this case with
JSONArray json = new JSONArray(data);
for (int i = 0; i <= json.length();i++){
JSONObject jsonObj = json.getJsonObject(i);
myModal modal = new myModal();
modal.setString(jsonObj.getString("name"));
//and so on
}
make sure to read the basics for understanding

Categories

Resources