how to output data from xampp to Textview - android

the code below I have successfully displayed the data but using the recyclerView. I want to ask how to display data if using Textview?
private void loadDataMahasiswa() {
progress = new ProgressDialog(this);
progress.setCancelable(false);
progress.setMessage("Loading ...");
progress.show();
String nip = editTxtnip.getText().toString();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
LoginAPI api = retrofit.create(LoginAPI.class);
Call<Value> call = api.view3(nip);
call.enqueue(new Callback<Value>() {
#Override
public void onResponse(Call<Value> call, Response<Value> response) {
String value = response.body().getValue();
progress.dismiss();
if (value.equals("1")) {
results = response.body().getResult();
viewAdapter = new RecyclerViewAdapter3(Lihat_izin.this, results);
recyclerView.setAdapter(viewAdapter);
}
}
#Override
public void onFailure(Call<Value> call, Throwable t) {
}
});
}
the results of the variables above are not readable sir
<?php
require_once('dbConnect.php');
date_default_timezone_set("Asia/Jakarta");
$timestamp = date('Y-m-d');
if($_SERVER['REQUEST_METHOD']=='GET')
$opd = $_GET['opd'];{
$sql = "SELECT COUNT(*)FROM(SELECT DISTINCT waktu,status from absen_pagi where opd='$opd' AND waktu='$timestamp')as dt";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result, array('waktu'=>$row['COUNT(*)']));
}
echo json_encode(array("value"=>1,"result"=>$result));
mysqli_close($con);
}
this my php json

If you are not using ArrayList of data then just add this line inside the response body
See below code
public void onResponse(Call<Value> call, Response<Value> response) {
String value = response.body().getValue();
progress.dismiss();
if (value.equals("1")) {
results = response.body().getResult();
viewAdapter = new RecyclerViewAdapter3(Lihat_izin.this, results);
recyclerView.setAdapter(viewAdapter);
String myData = response.body().toString(); // convert data to string
textView.setText(myData); // just add data to textView
}
}
Let me know if not solved yet

Related

Getting error while fetching an API through Retrofit , but same API is working with postman

This is the error we are facing
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 1119 path $.data[4].last_received_message
public void DeviceList(String api, final ApiType apiTypes, String page_no, String authtoken) {
ProgressDialog progressDialog = new ProgressDialog();
try {
this.pdLoading = progressDialog.getInstance(this.context);
this.pdLoading.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
if (this.pdLoading.isShowing()) {
this.pdLoading.cancel();
}
this.pdLoading.show();
} catch (Exception e) {
e.printStackTrace();
}
this.apiTypeVariable = apiTypes;
/*RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(api) //Setting the Root URL
.build();*/
Retrofit retrofit = new Retrofit.Builder().baseUrl(api).addConverterFactory(GsonConverterFactory.create()).client(okHttpClient).build();
GitApi gi = retrofit.create(GitApi.class);
call = (Call<T>) gi.getDevices(authtoken, page_no);
call.enqueue(new Callback<T>() {
#Override
public void onResponse(Call<T> call, Response<T> response) {
t = (T) response.body();
if (pdLoading.isShowing())
pdLoading.cancel();
onResponseListner.onResponse(t, apiTypeVariable, true);
}
#Override
public void onFailure(Call<T> call, Throwable t) {
Log.e(apiTypes.toString(), t.getMessage() + ".");
if (pdLoading.isShowing())
pdLoading.cancel();
onResponseListner.onResponse(null, apiTypeVariable, false);
}
});
}```
It tells that there is a problem occurred when convert json string to your model. Specifically, one of your model's properties is declared as String type but there is a field (key) of the json string maps to an object type. Please check the compatible of your model and the result you received from api

First name is not displaying in android using arraylist

Hi in the below first name is not passing correctly to another activity.Can any one help me.
I am comparing my username with user_name if both are equal then I am sending my first name to another activity.
Support my username is admin and user_name is admin then I am able to pass the first name from the api. If it is second list item it is not working.
private void fetchUserJSON(final String sessionId, final String username){
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Write code for your refresh logic
// progressDialog = new ProgressDialog(getActivity());
// progressDialog.setIndeterminate(true);
// progressDialog.setMessage("Loading...");
// progressDialog.setCanceledOnTouchOutside(false);
// progressDialog.setCancelable(false);
// progressDialog.show();
// sessionId = getIntent().getStringExtra("sessionId");
//username = getIntent().getStringExtra("username");
String operation = "query";
String query = "select * from Users";
final GetNoticeDataService service = RetrofitInstance.getRetrofitInstance().create(GetNoticeDataService.class);
/** Call the method with parameter in the interface to get the notice data*/
Call<UserModule> call = service.UserRecordDetails(operation, sessionId, query);
/**Log the URL called*/
Log.i("URL Called", call.request().url() + "");
call.enqueue(new Callback<UserModule>() {
#Override
public void onResponse(Call<UserModule> call, Response<UserModule> response) {
Log.e("response", new Gson().toJson(response.body()));
if (response.isSuccessful()) {
Log.e("response", new Gson().toJson(response.body()));
UserModule userModule = response.body();
String success = userModule.getSuccess();
if (success.equals("true")) {
Results_Users results = userModule.getResult();
records = results.getRecords();
for (Records records1 : records) {
String user_name = records1.getUser_name();
String id = records1.getId();
Log.d("id",id);
String first_name = records1.getFirst_name();
String last_name = records1.getLast_name();
String email1=records1.getEmail1();
String title=records1.getTitle();
Records records=new Records(user_name,title,first_name,last_name,email1,id);
recordsList.add(records);
}
if(username.equals(recordsList.get(0).getUser_name()))
i = new Intent(LoginActivity.this, MainActivity.class);
i.putExtra("first_name", recordsList.get(2).getFirst_name());
startActivity(i);
finish();
}
}
}
#Override
public void onFailure(Call<UserModule> call, Throwable t) {
}
// progressDialog.dismiss();
});
}
}, 0);
return ;
}
Remove final from for loop
for (Records records1 : records) {
I don't know the logic of your whole code. But you can edit your loop like this:
String first_name = null;
for (Records records1 : records) {
if (username.equals(records1.getUser_name())) {
first_name = records1.getFirst_name();
break;
}
}
i = new Intent(LoginActivity.this, MainActivity.class);
i.putExtra("first_name", first_name);
startActivity(i);
finish();

spinner list is not displaying in android

Hi in the below code fetching all the building details from API's .After getting the response from the server and then I am adding to the spinner.
In the below code want to display names of the building want to display in spinner.
below response want to display all the names in spinner list.
can any one help me where I did the mistake.
Response from server:
{
"list": [
{
"ID": "6",
"Name": "Microsoft1"
},
{
"ID": "9",
"Name": "building6567"
}
]
}
private void selectBuilding() {
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Write code for your refresh logic
progressDialog = new ProgressDialog (getActivity ());
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Communicating...");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setCancelable(false);
progressDialog.show();
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API.URL_BASE)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client (client)
.build();
API service = retrofit.create (API.class);
final Call<Managebuilding> userCall = service.getbuildinglist ();
userCall.enqueue(new Callback<Managebuilding> () {
#Override
public void onResponse(Call <Managebuilding> call, Response <Managebuilding> response) {
if (response != null && response.code ( ) == 200 && response.isSuccessful ( )) {
Managebuilding building = response.body ();
arrayList = new ArrayList <> ( );
arrayList.addAll(building.getList());
adapter = new ArrayAdapter<String>(getContext (), android.R.layout.simple_spinner_item, building.getList());///error
spinner.setAdapter(adapter);
/** Adding radio buttons for the spinner items */
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
progressDialog.dismiss ( );
} else {
progressDialog.dismiss ( );
Log.d ("Response errorBody", String.valueOf (response.errorBody ( )));
}
}
#Override
public void onFailure(Call<Managebuilding> call, Throwable t) {
// lv.setAdapter (adapter);
System.out.println("onFailure");
System.out.println(t.fillInStackTrace());
progressDialog.dismiss();
Toast.makeText(getActivity (), "Some error occurred -> ", Toast.LENGTH_LONG).show();;
// progressDialog.dismiss();
}
});
}
}, 5000);
return ;
}
Create a pojo class
public class SpinnerUtils {
public SpinnerUtils(String spinnerText, int value) {
this.spinnerText = spinnerText;
this.value = value;
}
public String getSpinnerText() {
return spinnerText;
}
public int getValue() {
return value;
}
public String toString() {
return spinnerText;
}
String spinnerText;
int value;
}
Then
SpinnerUtils items[]=new SpinnerUtils[array.length()];
items[i] = new SpinnerUtils(c.getString("name"), c.getInt("id"));
for (int i = 0; i <array.length(); i++) {
items[i] = new SpinnerUtils(c.getString("name"), c.getInt("id"));
}
ArrayAdapter<SpinnerUtils> adapter = new ArrayAdapter<SpinnerUtils>(this,android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(adapter);
where s is your spinner and array is the JSONArray retrieved from API. To retrieve the id:
SpinnerUtils d = items[position];
int standard = d.getValue();
Create the above 2 lines within the setOnItemSelectedListener of the spinner to get the id.Hope it will work.

Android-Openweathermap: list of cities after search

I'm just new to Android development and I'm trying to make a weather app where it shows list of countries with the city after making a search (ex. London). In openweathermap api, it shows 5 results with different countries with a name of "London" on it but in my codes it doesn't even show 1 result.
Here's my code:
public void getCityData(){
final Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
WeatherService weatherService = retrofit.create(WeatherService.class);
ListService listService = retrofit.create(ListService.class);
String cityName = search.getEditableText().toString();
stringArrayList.clear();
stringArrayList.add(cityName);
for (String city : stringArrayList) {
Call<WeatherData> weatherDataCall = weatherService.getWeatherData("/data/2.5/find?q=" + city + "&APPID=" + API_KEY + "");
weatherDataCall.enqueue(new Callback<WeatherData>() {
#Override
public void onResponse(Call<WeatherData> call, Response<WeatherData> response) {
ProgressBar progressBar = new ProgressBar(AddCityActivity.this, null, android.R.attr.progressBarStyleHorizontal);
progressBar.setIndeterminate(true);
WeatherData weatherData = response.body();
List<cp2.openweatherv3.model.List> lists = weatherData.getList();
for (int i = 0; i < lists.size(); i++){
Log.d("name", lists.get(i).getName());
Log.e("country", lists.get(i).getSys().getCountry());
Log.w("count", String.valueOf(lists.size()));
generateList(lists);
}
}
#Override
public void onFailure(Call<WeatherData> call, Throwable t) {
Log.d("sometag", t.getLocalizedMessage());
Toast.makeText(AddCityActivity.this, "not throwing anything", Toast.LENGTH_SHORT).show();
}
});
}
}
How can I make it possible?
Thank you so much

Dynamic URL Issue with retrofit

I want to fetch json files for different users according to their User_ID, but currently this code is showing empty recyclerview
Retrofit File
public void loadJSONClaim() {
Retrofit retrofitclaim = new Retrofit.Builder()
.baseUrl("http://ec2-54-191-118-200.us-west-2.compute.amazonaws.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
RequestInterfaceClaim requestclaim = retrofitclaim.create(RequestInterfaceClaim.class);
String User_ID = 5;
Call<JSONResponseClaim> call = requestclaim.getJSONClaim(User_ID);
call.enqueue(new Callback<JSONResponseClaim>() {
#Override
public void onResponse(Call<JSONResponseClaim> call, Response<JSONResponseClaim> responseclaim) {
JSONResponseClaim jsonResponseClaim = responseclaim.body();
dataclaim = new ArrayList<>(Arrays.asList(jsonResponseClaim.getAndroidClaim()));
adapterclaim = new DataAdapterClaim(dataclaim);
}
RequestInterFaceClaim
public interface RequestInterfaceClaim {
#GET("claim.php") // we want to access claim.php?User_ID=5
Call<JSONResponseClaim> getJSONClaim(#Query("User_ID") String User_ID);
}

Categories

Resources