Loading new JSON value using UI thread - android

I am facing problem while updating the new values fetched from json file after some interval (assume any either 5 second or any).I have developed this code and now I am stucked in this. When I run this code it shows the value after second run did not get updated the second time. I have implemented the handler but it is also not working here. I have used UI thread but I am facing problem again while using it.
public class MainActivity extends AppCompatActivity {
TextView a,b,c,d,e,f,g,h;
String result = "";
Handler mHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
a=(TextView) findViewById(R.id.a);
b=(TextView) findViewById(R.id.b);
c=(TextView) findViewById(R.id.c);
Runnable hand = new Runnable() {
#Override
public void run() {
DownloadTask task = new DownloadTask();
task.execute("https://api.thingspeak.com/channels/12345/feeds.json?results=1");
}
};
new Thread(hand).start();
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
}
#Override
protected void onPostExecute(final String result) {
super.onPostExecute(result);
Runnable handa = new Runnable() {
#Override
public void run() {
search(result);
}
};
new Thread(handa).start();
}
public void search(String result){
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray weatherInfo = jsonObject.getJSONArray("feeds");
JSONObject legsobject = weatherInfo.getJSONObject(0);
final String field1 = legsobject.getString("field1");
final String field2 = legsobject.getString("field2");
final String field3 = legsobject.getString("field3");
Thread.sleep(1000);
mHandler.post(new Runnable() {
#Override
public void run() {
a.setText(field1);
b.setText(field2);
c.setText(field3);
}
});
}
}
}
Can any one guide because I am beginner in Android and try to do practice. Need your help. Your guidance would help me to learn more.

Please try this
public class MainActivity extends AppCompatActivity {
TextView a,b,c,d,e,f,g,h;
String result = "";
Handler mHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
a=(TextView) findViewById(R.id.a);
b=(TextView) findViewById(R.id.b);
c=(TextView) findViewById(R.id.c);
DownloadTask task = new DownloadTask();
task.execute("https://api.thingspeak.com/channels/12345/feeds.json?results=1");
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
}
#Override
protected void onPostExecute(final String result) {
super.onPostExecute(result);
search(result);
}
public void search(String result){
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray weatherInfo = jsonObject.getJSONArray("feeds");
JSONObject legsobject = weatherInfo.getJSONObject(0);
final String field1 = legsobject.getString("field1");
final String field2 = legsobject.getString("field2");
final String field3 = legsobject.getString("field3");
a.setText(field1);
b.setText(field2);
c.setText(field3);
}
}
}

Related

How to Update recyclerView items after doInBackground

I'm using recyclerView in my app in which I'm calculating the route distance between the cities in other thread than UI thread. Now I want to refresh the recyclerView's distance field only whenever the distance is calculated.
TIA
public class DashboardAdapter extends RecyclerView.Adapter<DashboardAdapter.ListItemViewHolder> {
private List<DashBoardData> dashBoardData;
private Context context;
public DashboardAdapter(List<DashBoardData> dashBoardData, Context context) {
if (dashBoardData == null) {
throw new IllegalArgumentException("Data must not be null");
}
this.dashBoardData = dashBoardData;
this.context = context;
}
#NonNull
#Override
public ListItemViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_layout, viewGroup, false);
return new ListItemViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull ListItemViewHolder holder, int position) {
holder.tvSource.setText(dashBoardData.get(position).getSource());
holder.tvDestination.setText(dashBoardData.get(position).getDestination());
getDistance(context,
dashBoardData.get(position).getStartLocation(),
dashBoardData.get(position).getEndLocation());
holder.tvDistance.setText("");
}
#Override
public int getItemCount() {
return dashBoardData.size();
}
public final static class ListItemViewHolder extends RecyclerView.ViewHolder {
TextView tvSource, tvDestination, tvDistance;
public ListItemViewHolder(View itemView) {
super(itemView);
tvSource = (TextView) itemView.findViewById(R.id.tv_from_source);
tvDestination = (TextView) itemView.findViewById(R.id.tv_to_destination);
tvDistance = itemView.findViewById(R.id.tv_distance);
}
}
public static void getDistance(Context context, String srcLocation, String destLocation) {
String url = getDirectionsUrl(context, srcLocation, destLocation);
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(url);
}
public static class DownloadTask extends AsyncTask<String, Void, String> {
// Downloading data in non-ui thread
#Override
protected String doInBackground(String... url) {
String data = "";
try {
// Fetching the data from web service
String urlEncoded = (url[0]).replaceAll(" ", "");
data = downloadUrl(urlEncoded);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
private static String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception downloading url", e.toString());
} finally {
if (iStream != null) {
iStream.close();
}
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return data;
}
private static class ParserTask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... jsonData) {
JSONObject jObject;
String distance = "0 Mt";
try {
jObject = new JSONObject(jsonData[0]);
JSONArray jRoutes = null;
JSONArray jLegs = null;
jRoutes = jObject.getJSONArray("routes");
for (int i = 0; i < jRoutes.length(); i++) {
jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
for (int j = 0; j < jLegs.length(); j++) {
distance = (String) ((JSONObject)((JSONObject) jLegs.get(j)).get("distance")).get("text");
}
}
} catch (Exception e) {
e.printStackTrace();
}
return distance;
}
#Override
protected void onPostExecute(String result) {
//update ui
}
}
}
this is my adapter and I'm passing a dashboard list to this. After parsing the json data for distance I want to notify the distance field in onPostExecute() method.
The easiest way of doing that is once you are done updating all your data you call notify dataset changed on your adapter something like this:
//Some Code
mAdapter.notifyDataSetChanged();
Where mAdapter is the reference for your RecyclerView Adapter.

httpurl response code is blank in android studio

I am trying to get mysql data from remote server www.kudossoft.in/get_data030518.php. but i am getting nothing when i check httpurl response code that is blank.
i have also add uses permission for internet in mainifest
my code is following please see.
i have also checked my php files permission that is ok.
and i am also inserting some data from another activity in same database that is working properly.
MainActivity code:
public class MainActivity extends AppCompatActivity {
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
getJSON("http://kudossoft.in/get_data300518.php");
}
private void getJSON(final String urlWebService) {
class GetJSON extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
try {
loadIntoListView(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(urlWebService);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetJSON getJSON = new GetJSON();
getJSON.execute();
}
private void loadIntoListView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
String[] heroes = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
heroes[i] = obj.getString("name");``
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, heroes);
listView.setAdapter(arrayAdapter);
}
}

How to update values fetching from api at real time?

I making a quiz app in which i am displaying question and it's four option in radio buttons,i want to display question one by one by updating it to the next id question on a click of button.....How should i do that? and also how should i check score for it which i want to display on the next activity i will make? the app crashes on the listner of button
Thanks in advance!
QuizActivity:
public class Quiz extends AppCompatActivity {
RadioGroup radioGroup;
RadioButton optionOne,optionTwo,optionThree,optionFour;
private TextView questionName;
String question_name;
String option1,option2,option3,option4;
Button next_question;
int first_question_index=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
questionName=(TextView)findViewById(R.id.question_name);
radioGroup =(RadioGroup)findViewById(R.id.radioGroup);
optionOne=(RadioButton)findViewById(R.id.answerOne);
optionTwo=(RadioButton)findViewById(R.id.answerOne);
optionThree=(RadioButton)findViewById(R.id.answerOne);
optionFour=(RadioButton)findViewById(R.id.answerOne);
next_question=(Button)findViewById(R.id.button_next_question);
FetchLists fetchLists =new FetchLists();
fetchLists.execute(10,0);
next_question.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
first_question_index++;
}
}); }
public class FetchLists extends AsyncTask<Integer, Void, String> {
#Override
protected String doInBackground(Integer... params) {
String urlString = "http://aptronnoida.com/Aditya_July4/Demo/JAVA_FETCH.php";
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStream stream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line = reader.readLine();
String response = "";
while (line != null) {
response += line;
line = reader.readLine();
}
JSONObject object = new JSONObject(response);
JSONArray jsonArray = object.getJSONArray("data");
JSONObject list = (JSONObject) jsonArray.get(first_question_index);
question_name= list.getString("Question");
option1=list.getString("A1");
option2=list.getString("A2");
option3=list.getString("A3");
option4=list.getString("A4");
} catch (Exception e) {
e.printStackTrace();
}
return "quiz";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
questionName.setText(question_name);
((RadioButton) radioGroup.getChildAt(0)).setText(option1);
((RadioButton) radioGroup.getChildAt(1)).setText(option2);
((RadioButton) radioGroup.getChildAt(2)).setText(option3);
((RadioButton) radioGroup.getChildAt(3)).setText(option4);
}
}
}
public class Quiz extends AppCompatActivity {
RadioGroup radioGroup;
RadioButton optionOne,optionTwo,optionThree,optionFour;
private TextView questionName;
String question_name;
String option1,option2,option3,option4;
Button next_question;
int first_question_index=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
questionName=(TextView)findViewById(R.id.question_name);
radioGroup =(RadioGroup)findViewById(R.id.radioGroup);
optionOne=(RadioButton)findViewById(R.id.answerOne);
optionTwo=(RadioButton)findViewById(R.id.answerOne);
optionThree=(RadioButton)findViewById(R.id.answerOne);
optionFour=(RadioButton)findViewById(R.id.answerOne);
next_question=(Button)findViewById(R.id.button_next_question);
next_question.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
first_question_index++;
FetchLists fetchLists = new FetchLists();
fetchLists.execute(10, 0);
}
});
FetchLists fetchLists = new FetchLists();
fetchLists.execute(10, 0);
}
public class FetchLists extends AsyncTask<Integer, Void, String> {
#Override
protected String doInBackground(Integer... params) {
String urlString = "http://aptronnoida.com/Aditya_July4/Demo/JAVA_FETCH.php";
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
InputStream stream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line = reader.readLine();
String response = "";
while (line != null) {
response += line;
line = reader.readLine();
}
JSONObject object = new JSONObject(response);
JSONArray jsonArray = object.getJSONArray("data");
JSONObject list = (JSONObject) jsonArray.get(first_question_index);
Log.d("ashu","JsonObject "+list);
question_name= list.getString("Question");
option1=list.getString("A1");
option2=list.getString("A2");
option3=list.getString("A3");
option4=list.getString("A4");
} catch (Exception e) {
e.printStackTrace();
}
return "quiz";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
questionName.setText(question_name);
((RadioButton) radioGroup.getChildAt(0)).setText(option1);
((RadioButton) radioGroup.getChildAt(1)).setText(option2);
((RadioButton) radioGroup.getChildAt(2)).setText(option3);
((RadioButton) radioGroup.getChildAt(3)).setText(option4);
}
}
}

AsyncTask doInBackground does not execute

I tried almost all the solution but there's some problem with my Inner AsyncTask class. It seems that doInBackground() is not being executed.
onPreExecute() and onPostExecute()are working. However, doInBackground() does not read the code.
I'm really sure about getJSON() is correct 100% because i used the same code before
this is my class
public class My extends Activity implements Runnable {
public static String s = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
findViewById(android.R.id.content).postDelayed(this, 3000);
getJSON("My link ");
}
#Override
public void run() {
startActivity(new Intent(SplashActivity.this, MainActivity.class));
finish();
}
}
AsyncTask:
private void getJSON(String url) {
class GetJSON extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while((json = bufferedReader.readLine())!= null){
sb.append(json+"\n");
}
s = sb.toString().trim();
return sb.toString().trim();
} catch(Exception e){
return null;
}
}
#Override
protected void onPostExecute(String ss) {
super.onPostExecute(ss);
s = ss;
}
}
GetJSON gj = new GetJSON();
gj.execute(url);
}
Thanks

JSON returns data in one code and null in other

I have an app that connects to server sends sql request and get JSON answer as JsonArray.
Its Asynktask in seperate class (HTTPRequest.java is my AsyncTask class, Responce.java its my callback interface class) and it works correct.
when I use it in OrderActivity.java like below
#Override //my interface class function
public void onPostExecute(JSONArray Result) {
load(Result);
}
private void load(JSONArray json) {
for(int i=0;i<json.length();i++){
try {
JSONObject jo = json.getJSONObject(i);
Product p = new Product(
jo.getInt("ID"),
jo.getInt("parent"),
jo.getInt("category"),
jo.getString("Item"),
jo.getDouble("Price")
);
products.add(p);
} catch (JSONException e) {
e.printStackTrace();
}
}
it does work and fills product with data, but when I assign to my class variable JSONArray json
JSONArray json = new JSONArray;
.
.
.
#Override
public void onPostExecute(JSONArray Result) {
json = Result;
}
json is null
//HTTPRequest.java
public class HTTPRequest extends AsyncTask<String, Void, Integer> {
private Context context;
private Responce responce;
JSONArray json;
public HTTPRequest(Context context){
this.context = context;
responce = (Responce)context;
}
#Override
protected Integer doInBackground(String... params) {
OutputStream output;
InputStream inputStream = null;
HttpURLConnection connection = null;
String charset = "UTF-8";
Integer result = 0;
try {
URL uri = new URL(params[0]);
connection = (HttpURLConnection) uri.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "text/plain; charset=" + charset);
output = connection.getOutputStream();
output.write(params[1].getBytes(charset));
output.close();
int statusCode = connection.getResponseCode();
if (statusCode == 200) {
inputStream = new BufferedInputStream(connection.getInputStream());
json = new JSONArray(getJSON(inputStream));
result = 1;
}
} catch (Exception e) {
e.getLocalizedMessage();
}
return result;
}
#Override
protected void onPostExecute(Integer i) {
super.onPostExecute(i);
if(i == 1) {
responce.onPostExecute(json);
} else {
responce.onPostExecute(null);
}
}
private String getJSON(InputStream inputStream) throws IOException, JSONException {
StringBuffer stringBuffer = new StringBuffer();
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = null;
while((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line.toString());
}
result = stringBuffer.toString();
if(null!=inputStream){
inputStream.close();
}
return result;
}
}
//Responce.java
public interface Responce {
public void onPostExecute(JSONArray Result);
}
//OrderActivity.java
public class OrderActivity extends Activity implements Responce{
ArrayList<Product> products = new ArrayList<Product>();
ProductAdapter productAdapter;
OrderItemAdapter orderItemAdapter;
ListView orderlist;
JSONArray ja;
Button btnBack;
Button btnTakeOrder;
ListView picklist;
HTTPRequest httpRequest;
String url = "http://192.168.3.125:8888/data/";
String query = "select * from vwitems order by category desc";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
orderlist =(ListView)findViewById(R.id.orderlist);
orderItemAdapter = new OrderItemAdapter(OrderActivity.this);
btnBack = (Button)findViewById(R.id.btnBack);
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
productAdapter.filter(0);
}
});
btnTakeOrder = (Button)findViewById(R.id.btnTakeOrder);
btnTakeOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer oid = 0;
Order order = new Order(OrderActivity.this);
oid = order.NewOrder(1, 2, 3);
Toast.makeText(OrderActivity.this," " + order.getCount(), LENGTH_SHORT).show();
}
});
orderlist.setAdapter(orderItemAdapter);
picklist = (ListView) findViewById(R.id.picklist);
picklist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int pid = 0;
if (productAdapter.getItem(position).isCategory()) {
pid = productAdapter.getItem(position).getId();
productAdapter.filter(pid);
} else {
OrderItem oi = new OrderItem();
oi.setItemId(productAdapter.getItem(position).getId());
oi.setItem(productAdapter.getItem(position).getItem());
oi.setPrice(productAdapter.getItem(position).getPrice());
search(oi);
}
}
});
httpRequest = new HTTPRequest(this);
httpRequest.execute(url, query);
}
private boolean search(OrderItem oi){
int size = orderItemAdapter.getCount();
int i = 0;
if(size != 0)
for(OrderItem o : orderItemAdapter.getAll()){
if(o.getItemId() == oi.getItemId()){
orderItemAdapter.getItem(i).setQuantity(orderItemAdapter.getItem(i).getQuantity() + 1);
orderItemAdapter.notifyDataSetChanged();
return true;
}
i++;
}
orderItemAdapter.addItem(oi);
orderItemAdapter.notifyDataSetChanged();
return false;
}
private void load(JSONArray json) {
for(int i=0;i<json.length();i++){
try {
JSONObject jo = json.getJSONObject(i);
Product p = new Product(
jo.getInt("ID"),
jo.getInt("parent"),
jo.getInt("category"),
jo.getString("Item"),
jo.getDouble("Price")
);
products.add(p);
} catch (JSONException e) {
e.printStackTrace();
}
}
productAdapter = new ProductAdapter(OrderActivity.this, products);
picklist.setAdapter(productAdapter);
productAdapter.filter(0);
}
#Override
public void onPostExecute(JSONArray Result) {
load(Result);
}
/*
#Override
public void onPostExecute(JSONArray Result) {
json = Result;
}
**/
}
sorry i forgot include this one
//Order.java
public class Order implements Responce{
private Context context;
private JSONArray json = new JSONArray();
private HTTPRequest httpRequest;
private int OrderID;
private Date OrderDate;
private int OrderTable;
private int Waiter;
private byte OrderStatus;
private List<OrderItem> orderItems;
public Order(Context context){
this.context = context;
}
//some code here...
public Integer NewOrder(Integer guests, Integer waiter, Integer ordertable){
String query = "insert into orders(orderdate, guests, waiter, ordertable) VALUES(NOW()," + guests + ", " + waiter + ", " + ordertable + "); SELECT LAST_INSERT_ID() as ID;";
Integer result = 0;
Connect(query);
try {
JSONObject jo = json.getJSONObject(0);
result = jo.getInt("ID");
} catch (JSONException e) {
e.printStackTrace();
}
return result; //here i got 0 if i init result to 0, null or what ever i init my
}
#Override
public void onPostExecute(JSONArray Result) {
json = Result;
}
private void Connect (String query){
httpRequest = new HTTPRequest(context);
httpRequest.execute("http://192.168.3.125:8888/data/", query);
}
}

Categories

Resources