How to update values fetching from api at real time? - android

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

Related

My UI is not updating after API call of openweather

I want to parse JSON from the Openweather API but after many iterations and debugging, my JSON string is not updating, I do not think that there is any problem still the temperatures( minTemperature and maxTemperature) and the name of the place(mPlace) is not set, also I logged the maxtemperature but the console is showing nothing please look into my code.
public class MainActivity extends AppCompatActivity {
private EditText placeText;
private Button enterPlaceButton;
private TextView minTemperature;
private TextView maxTemperature;
private TextView mPlace;
private static final String AppID ="56a5e01eba3af36a7a9b7b210a437d09";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle("Weather");
placeText = findViewById(R.id.myPlaceEditText);
enterPlaceButton = findViewById(R.id.enterPlace);
minTemperature = findViewById(R.id.minTemperature);
maxTemperature = findViewById(R.id.maxTemperature);
mPlace = findViewById(R.id.mPlace);
}
#Override
protected void onResume() {
final URL[] url = {null};
enterPlaceButton.setOnClickListener(v -> {
url[0] = makeUrl(placeText.getText().toString());
placeText.setText("");
});
if (url[0] != null) {
MyAsync myAsync = new MyAsync();
myAsync.execute(url[0]);
}
super.onResume();
}
public URL makeUrl(String place) {
Uri.Builder uriBuilder = new Uri.Builder();
uriBuilder.scheme("http");
uriBuilder.authority("api.openweathermap.org/");
uriBuilder.appendPath("data");
uriBuilder.appendPath("2.5");
uriBuilder.appendPath("weather");
uriBuilder.appendQueryParameter("q",place);
uriBuilder.appendQueryParameter("appid",AppID);
try {
return new URL(uriBuilder.build().toString());
} catch (MalformedURLException e) {
Toast.makeText(MainActivity.this, "Sorry could not able to fetch the Data", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
return null;
}
public class MyAsync extends AsyncTask<URL, Void, String> {
#Override
protected String doInBackground(URL... urls) {
StringBuilder jsonResponseBuilder = new StringBuilder();
try {
HttpURLConnection httpURLConnection = (HttpURLConnection) urls[0].openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setConnectTimeout(15000);
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == 200) {
InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = bufferedReader.readLine();
while (line != null) {
jsonResponseBuilder.append(line);
line = bufferedReader.readLine();
}
httpURLConnection.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Sorry could not able to fetch the Data", Toast.LENGTH_SHORT).show();
}
Log.d(MyAsync.class.getName(),jsonResponseBuilder.toString());
return jsonResponseBuilder.toString();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
setDataFromJSON(s);
super.onPostExecute(s);
}
public void setDataFromJSON(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
JSONObject getMainObject = jsonObject.getJSONObject("main");
String maxTemp = getMainObject.getString("temp_max");
Log.i(MainActivity.class.getName(), maxTemp);
maxTemperature.setText(maxTemp);
String minTemp = getMainObject.getString("temp_min");
minTemperature.setText(minTemp);
mPlace.setText(jsonObject.getString("name"));
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Sorry could not able to fetch the Data", Toast.LENGTH_SHORT).show();
}
}
}
}

Loading new JSON value using UI thread

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

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

while navigating to the next page from login page, blank screen appears

I have integrated a webservice and after integrating it goes to the next page.
But the problem is while navigating to from login page to next page, it is showing blank screen and I do not understand what's the problem.
Kindly Help!!
Thanks in advance.
Here is my code
public class Mobile_Number_Activity extends Activity {
private EditText ed_Mobile_Number;
private Button btnSubmit;
private TextView Hyperlink;
private ProgressDialog pDialog;
private JSONObject json;
private int success = 0;
private String path = "xxx";
private String strMobileNumber = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mobile_number);
ed_Mobile_Number = (EditText) findViewById(R.id.ed_Mobile_Number);
btnSubmit = (Button) findViewById(R.id.btn_mobile_submit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if (!ed_Mobile_Number.getText().toString().equals(""))
{
strMobileNumber = ed_Mobile_Number.getText().toString();
new SendPostRequest(getApplicationContext()).execute(strMobileNumber);
}
else
{
Toast.makeText(getApplicationContext(), "Please Enter Mobile Number", Toast.LENGTH_LONG).show();
}
}
});
}
Here is SendPost Request Class which extends Asyntask
public class SendPostRequest extends AsyncTask<String, Void, String> {
public static ProgressDialog pDialog;
private String path = "xxxx";
public String Mobile_Number = "";
private Context mContext;
public SendPostRequest(Context context)
{
this.mContext=context;
pDialog = new ProgressDialog(mContext);
pDialog.setTitle("Loading...");
pDialog.setMessage("Please wait...");
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.show();
}
#Override
protected String doInBackground(String... arg0)
{
try
{
Thread.sleep(40000);
String m_number=arg0[0];
URL url = new URL(path); // here is your URL path
JSONObject postDataParams = new JSONObject();
postDataParams.put("username", "data");
postDataParams.put("password", "data");
postDataParams.put("mobile", m_number);
System.out.println(m_number);
Mobile_Number=m_number;
Log.e("params", postDataParams.toString());
//conversion of 15 min to miliseconds :900000
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// conn.setReadTimeout(1500/* milliseconds */);
//conn.setConnectTimeout(1500 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
} else {
return new String("false : " + responseCode);
}
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
if (pDialog != null && pDialog.isShowing()) {
//Toast.makeText(mContext.getApplicationContext(), result,Toast.LENGTH_LONG).show();
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(result);
String otp = jsonObject.optString("otp");
Log.d("otp value is", otp);
message(otp);
} catch (JSONException e) {
e.printStackTrace();
}
pDialog.dismiss();
}
}
public String getPostDataString(JSONObject params) throws Exception {
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while (itr.hasNext()) {
String key = itr.next();
Object value = params.get(key);
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
}
return result.toString();
}
public void message(String otp)
{
Intent myIntent = new Intent(this.mContext,OTP_Code_Activity.class);
myIntent.putExtra("Mobile Number", Mobile_Number);
System.out.println(Mobile_Number);
myIntent.putExtra("OTP Code", otp);
mContext.startActivity(myIntent);
pDialog.dismiss();
}
new SendPostRequest(getApplicationContext()).execute(strMobileNumber);
Change this to activity context.
new SendPostRequest(Mobile_Number_Activity.this).execute(strMobileNumber);
Delete(uninstall) the app from your phone, and run it again..It happens due to some issues with database. Or else I think you haven't mention the activity in the Manifest
Change
new SendPostRequest(getApplicationContext()).execute(strMobileNumber);
To
new SendPostRequest(this).execute(strMobileNumber);
And with Application Context, you can't show Dialog. You need to use Activity instance.
Change
SendPostRequest(Context context)
To
SendPostRequest(Activity context)
It might be helpful. Check log and see have any error in JSON Parse Exception as well.

how to call a web service in android [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
i need to call a web service from the url. wen i entered the no in the text box i should the output which i entered in text box. pls help me fixing the errors. here is my java code.
MainActivity.java
public class MainActivity extends Activity {
Button b;
TextView tv;
EditText et;
String editText;
String displayText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.editText1);
tv = (TextView) findViewById(R.id.tv_result);
b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (et.getText().length() != 0 && et.getText().toString() != "") {
editText = et.getText().toString();
AsyncCallWS task = new AsyncCallWS();
task.execute();
} else {
tv.setText("Please enter number");
}
}
});
}
private class AsyncCallWS extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
displayText = ser.invokeiop(editText,"hello");
return null;
}
}
}
ser.java
public class ser {
private static String NAMESPACE = "http://tempuri.org/";
private static String URL = "http://my url";
private static String SOAP_ACTION = "srvice";
public static String invokeiop(String name, String webMethName) {
String resTxt = null;
SoapObject request = new SoapObject(NAMESPACE, webMethName);
PropertyInfo iop = new PropertyInfo();
iop.setName("name");
iop.setValue(name);
//iop.setType(String.class);
request.addProperty(iop);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION+webMethName, envelope);
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
resTxt = response.toString();
} catch (Exception e) {
e.printStackTrace();
resTxt = "Error occured";
}
This might help you!!
public class MainActivity extends Activity {
Button b;
EditText et;
String editText;
String displayText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.editText1);
b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (et.getText().length() != 0 && et.getText().toString() != "") {
editText = et.getText().toString();
AsyncCallWS();
} else {
// declare a toast
}
}
});
}
public void AsyncCallWS(final String q)
{
class HttpGetAsyncTask extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... params)
{
String txtSearch = params[0];
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("URL"+editText);
try
{
HttpResponse httpResponse = httpClient.execute(httpGet);
inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder strB = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null)
{
strB.append(bufferedStrChunk);
}
return strB.toString();
}
catch (ClientProtocolException cpe)
{
cpe.printStackTrace();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
try {
// Parse your data here
}
catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
}
}
HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask();
httpGetAsyncTask.execute(editText);
}

Categories

Resources