Use Json in Fragment (textView) from OkHttp Request in seperate class - java

If the button in DietFragment is pressed, it runs the getJson() method in HttpRequestDietPlan. Afterwards the Json(mealId, title) is used in the DietFragment.
Problem: DietFragment doesn't wait for the Request to finish.
Future isn't possible because lowest Android version needs to be 4.4
DietFragment
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class DietFragment extends Fragment {
Button button;
TextView mealOne;
public int mealId;
public DietPlan dietPlan = new DietPlan();
HttpRequestDietPlan hrt = new HttpRequestDietPlan();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_diet, null);
ET = rootView.findViewById(R.id.targetCalories_Input);
Tv1 = rootView.findViewById(R.id.targetCalories_Output);
button = rootView.findViewById(R.id.testButton);
mealOne = rootView.findViewById(R.id.meal1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hrt.getJson();
// java.lang.IllegalMonitorStateException: object not locked by thread before wait()
mealId = hrt.dietPlan.meals.get(0).mealId;
title = hrt.dietPlan.meals.get(0).title;
mealOne.setText(title);
}
});
return rootView;
}
}
HttpRequestDietPlan
import android.os.Build;
import android.support.annotation.RequiresApi;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class HttpRequestDietPlan {
public DietPlan dietPlan = new DietPlan();
public final CompletableFuture<Response> future = new CompletableFuture<>();
public void getJson() {
OkHttpClient client = new OkHttpClient();
final Request request = new Request.Builder()
.addHeader("X-RapidAPI-Host", "spoonacular-recipe-food-nutrition-v1.p.rapidapi.com")
.addHeader("X-RapidAPI-Key", "KEY_KEY_KEY")
.url("https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/mealplans/generate?timeFrame=day&targetCalories=2000")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
call.cancel();
e.printStackTrace();
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
} else {
try {
String jsonData = response.body().string();
JSONObject json = new JSONObject(jsonData);
JSONArray arrayMeals = json.getJSONArray("meals");
for (int i = 0; i < arrayMeals.length(); i++) {
JSONObject object = arrayMeals.getJSONObject(i);
Meal meal = new Meal(
object.getInt("id"),
object.getString("title")
);
dietPlan.meals.add(meal);
System.out.println(meal);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
}
}

Here are some suggestions:
You don't need to create a new OkHttpClient at each call, so I moved it outside the method.
Then you can pass a callback (CallHandler) to be notified when the result of the call will be available, and update your data after the result is received.
One more thing, about the deserialization, I suggest you to use a library (https://github.com/google/gson) to deserialize your json response to an instance of a class.
PS: I didn't test this code, this is just a implementation suggestion.
Fragment:
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class DietFragment extends Fragment {
Button button;
TextView mealOne;
public int mealId;
public DietPlan dietPlan = new DietPlan();
HttpRequestDietPlan hrt = new HttpRequestDietPlan();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_diet, null);
ET = rootView.findViewById(R.id.targetCalories_Input);
Tv1 = rootView.findViewById(R.id.targetCalories_Output);
button = rootView.findViewById(R.id.testButton);
mealOne = rootView.findViewById(R.id.meal1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hrt.getJson(new HttpRequestDietPlan.CallHandler(
#Override
public void onFailure(Exception e) {
e.printStackTrace();
}
#Override
public void onSuccess(DietPlan dietPlan) {
mealId = hrt.dietPlan.meals.get(0).mealId;
title = hrt.dietPlan.meals.get(0).title;
mealOne.setText(title);
}
));
}
});
return rootView;
}
}
HttpRequestDietPlan:
import android.os.Build;
import android.support.annotation.RequiresApi;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class HttpRequestDietPlan {
private OkHttpClient client = new OkHttpClient();
public interface CallHandler {
public void onSuccess(DietPlan dietPlan);
public void onFailure(Exception e);
}
public void getJson(CallHandler callHandler) {
final Request request = new Request.Builder()
.addHeader("X-RapidAPI-Host", "spoonacular-recipe-food-nutrition-v1.p.rapidapi.com")
.addHeader("X-RapidAPI-Key", "KEY_KEY_KEY")
.url("https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/mealplans/generate?timeFrame=day&targetCalories=2000")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
call.cancel();
e.printStackTrace();
callHandler.onFailure(e)
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
if (!response.isSuccessful()) {
IOException e = new IOException("Unexpected code " + response);
callHandler.onFailure(e)
} else {
DietPlan dietPlan = new DietPlan();
// Deserialize with a library here
try {
String jsonData = response.body().string();
JSONObject json = new JSONObject(jsonData);
JSONArray arrayMeals = json.getJSONArray("meals");
for (int i = 0; i < arrayMeals.length(); i++) {
JSONObject object = arrayMeals.getJSONObject(i);
Meal meal = new Meal(
object.getInt("id"),
object.getString("title")
);
dietPlan.meals.add(meal);
System.out.println(meal);
}
} catch (JSONException e) {
e.printStackTrace();
}
callHandler.onSuccess(dietPlan)
}
}
});
}
}

Related

Problem to implement API in Android Studio

I need help to implement a list view from an API,
i need one more list to complete and make a get method.
This is for a project for faculty and i dont see solution on tutorials on internet
Here is code for information view :
package com.example.myapplication;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.gms.common.api.Api;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.io.File;
import java.io.IOException;
import javax.net.ssl.HttpsURLConnection;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
public class TopScorer extends AppCompatActivity {
SearchView searchView;
ListView listView;
String teams[] = {};
ArrayAdapter<String> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_top_scorer);
searchView = findViewById(R.id.search);
listView = findViewById(R.id.listview);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
ArrayList<String> teamsInf = new ArrayList<>();
#Override
public boolean onQueryTextSubmit(String query) {
API API = new API(query);
try {
API.execute().get();
teamsInf = API.getTeamsInfo();
arrayAdapter = new ArrayAdapter<String>(TopScorer.this, android.R.layout.simple_list_item_1, teamsInf);
listView.setAdapter(arrayAdapter);
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
return true;
}
});
}
public class API extends AsyncTask {
String teamName;
ArrayList<String> teamsInfo;
public API(String name) {
this.teamsInfo = new ArrayList<>();
}
#Override
protected Object doInBackground(Object[] objects) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://heisenbug-premier-league-live-scores-v1.p.rapidapi.com/api/premierleague/team?name="+this.teamName)
.get()
.addHeader("X-RapidAPI-Key", "6ad8dfcfcbmshb4a45a22532e4a1p1efecajsnc2fb433de0da")
.addHeader("X-RapidAPI-Host", "heisenbug-premier-league-live-scores-v1.p.rapidapi.com")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(#NonNull Call call, #NonNull IOException e) {
Toast.makeText(TopScorer.this, "Error", Toast.LENGTH_SHORT).show();
}
#Override
public void onResponse(#NonNull Call call, #NonNull Response response) throws IOException {
int index=1;
String myResult = response.body().string();
Gson gson = new Gson();
Data responseResult=gson.fromJson(myResult, Data.class);
for (lst l : responseResult.Data())
{
Log.d(TAG, "Liverpool: " + l.getTeam());
teamsInfo.add(String.valueOf(index) + ". " + l.getPlayed() + ": " + l.getWin());
teamsInfo.add("Draws : " + l.getDraw());
teamsInfo.add("Loss : " + l.getLoss());
teamsInfo.add("Goals Against : " + l.getGoalsAgainst());
teamsInfo.add("Goals For : " + l.getGoalsFor());
teamsInfo.add("Points : " + l.getPoints());
teamsInfo.add("");
index++;
}
}
});
return null;
}
public ArrayList<String> getTeamsInfo()
{
return this.teamsInfo;
}
}
}
and here is Data Class code:
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Data {
private String team;
private String played;
private String win;
private String draw;
private String loss;
private String goalsFor;
private String goalsAgainst;
private String points;
public String getTeam() {
return this.team;
}
public String getPlayed() {
return this.played;
}
public String getWin() {
return this.win;
}
public String getDraw() {
return this.draw;
}
public String getLoss() {
return this.loss;
}
public String getGoalsFor() {
return this.goalsFor;
}
public String getGoalsAgainst() {
return this.goalsAgainst;
}
public String getPoints() {
return this.points;
}
public Data fromJson(JSONObject jsonObject) {
Data team = new Data();
try {
team.team = jsonObject.getString("team");
team.played = jsonObject.getString("played");
team.win = jsonObject.getString("win");
team.draw = jsonObject.getString("draw");
team.loss = jsonObject.getString("loss");
team.goalsFor = jsonObject.getString("goalsFor");
team.goalsAgainst = jsonObject.getString("goalsAgainst");
team.points = jsonObject.getString("points");
} catch (JSONException e) {
e.printStackTrace();
return null;
}
return team;
}
}
can anyone help me, i prefered to implement api respone with okhttp code

why okhttp3 client.execute does not work?

I have a simple flask app that takes an image and return prediction from keras model
flask code
#app.route('/route', methods=['GET','POST'])
def rose():
model = load_model('model.h5')
model.compile(loss='categorical_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
img_width, img_height = 128, 128
img = Image.open(request.files['file'])
if img.mode != "RGB":
img.convert("RGB")
img = img.resize((img_width, img_height))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
images = np.vstack([x])
classes = model.predict(images)
return str(classes )
I need to upload the image from an android application using camerakit-android: here is my code:
package com.bostanji.wardeh.ui.home;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.Image;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import com.bostanji.wardeh.R;
import com.wonderkiln.camerakit.CameraKitError;
import com.wonderkiln.camerakit.CameraKitEvent;
import com.wonderkiln.camerakit.CameraKitEventListener;
import com.wonderkiln.camerakit.CameraKitImage;
import com.wonderkiln.camerakit.CameraKitVideo;
import com.wonderkiln.camerakit.CameraView;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.TimeUnit;
import dmax.dialog.SpotsDialog;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class HomeFragment extends Fragment {
private CameraView cameraView;
private Button button;
private AlertDialog waitingDialog;
private Dialog emptyDialog;
#Override
public void onResume() {
super.onResume();
cameraView.start();
}
#Override
public void onPause() {
super.onPause();
cameraView.stop();
}
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_home, container, false);
cameraView = root.findViewById(R.id.camera);
button = root.findViewById(R.id.btn_detect);
waitingDialog = new SpotsDialog.Builder().setContext(getContext()).setMessage("Please wait").setCancelable(false).build();
cameraView.addCameraKitListener(new CameraKitEventListener() {
#Override
public void onEvent(CameraKitEvent cameraKitEvent) {
}
#Override
public void onError(CameraKitError cameraKitError) {
}
#Override
public void onImage(final CameraKitImage cameraKitImage) {
//waitingDialog.show();
Bitmap bitmap = cameraKitImage.getBitmap();
final byte[] img = cameraKitImage.getJpeg();
final Bitmap uploadMap = bitmap;
bitmap = Bitmap.createScaledBitmap(bitmap, cameraView.getWidth(), cameraView.getHeight(), false);
cameraView.stop();
waitingDialog.show();
final Handler handler = new Handler();
new Thread(){
#Override
public void run() {
try {
OkHttpClient client = new OkHttpClient();
String postUrl= "flaskapp.com/route";
final MediaType MEDIA_TYPE_JPEG = MediaType.parse("image/jpeg");
RequestBody req = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("file","rose.jpeg", RequestBody.create(img, MEDIA_TYPE_JPEG)).build();
Request request = new Request.Builder()
.url(postUrl)
.post(req)
.build();
try {
Response response = client.newCall(request).execute();
final String r = response.body().string();
handler.post(new Runnable() {
#Override
public void run() {
waitingDialog.dismiss();
Toast.makeText(getContext(), r, Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
}
}
}.start();
}
#Override
public void onVideo(CameraKitVideo cameraKitVideo) {
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cameraView.start();
cameraView.captureImage();
}
});
return root;
}
}
once I click the button to take a picture and upload it the waiting dialog show and stays like this for ever.
P.S I don't need to send in the post request anything else other than the image and wait for the response
You use a deprecated constructor, which is error prone. It would be better to use final Handler handler = new Handler(Looper.getMainLooper());
Furthermore you just post your message when the post request was successful. If it's not successful, the waiting dialog will stay forever.
So it would update your code:
#Override
public void onImage(final CameraKitImage cameraKitImage) {
//waitingDialog.show();
Bitmap bitmap = cameraKitImage.getBitmap();
final byte[] img = cameraKitImage.getJpeg();
final Bitmap uploadMap = bitmap;
bitmap = Bitmap.createScaledBitmap(bitmap, cameraView.getWidth(), cameraView.getHeight(), false);
cameraView.stop();
waitingDialog.show();
final Handler handler = new Handler(Looper.getMainLooper());
new Thread(){
#Override
public void run() {
try {
OkHttpClient client = new OkHttpClient();
String postUrl= "flaskapp.com/route";
final MediaType MEDIA_TYPE_JPEG = MediaType.parse("image/jpeg");
RequestBody req = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("file","rose.jpeg", RequestBody.create(img, MEDIA_TYPE_JPEG)).build();
Request request = new Request.Builder()
.url(postUrl)
.post(req)
.build();
Response response = client.newCall(request).execute();
final String r = response.body().string();
} catch (Exception e) {
Log.e('Camera', 'POST failed', e);
} finally {
handler.post(new Runnable() {
#Override
public void run() {
waitingDialog.dismiss();
Toast.makeText(getContext(), r, Toast.LENGTH_LONG).show();
}
});
}
}.start();
}

Can't delete and create data on Fragment Activity [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm trying to delete and create a data string from a API webpage but i can't get the error code
I create API website from native php. But i create data on postman work insert and delete data
Code Delete Data
package com.dev.kedaiit.sibooks.ui.kategori;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.dev.kedaiit.sibooks.MainActivity;
import com.dev.kedaiit.sibooks.R;
import com.dev.kedaiit.sibooks.util.AppController;
import com.dev.kedaiit.sibooks.util.ServerAPI;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class DeleteKategori extends AppCompatActivity {
EditText deleteID ;
Button btnDelete;
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delete_kategori);
deleteID = (EditText) findViewById(R.id.id_kategori);
btnDelete = (Button) findViewById(R.id.btn_delete);
pd = new ProgressDialog(DeleteKategori.this);
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
deleteData();
}
});
}
private void deleteData()
{
pd.setMessage("Delete Data ...");
pd.setCancelable(true);
pd.show();
StringRequest delReq = new StringRequest(Request.Method.POST, ServerAPI.URL_DELETE_KATEGORI, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pd.cancel();
Log.d("volley","response : " + response.toString());
try {
JSONObject res = new JSONObject(response);
Toast.makeText(DeleteKategori.this,"Successs" +res.getString("message"), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
startActivity(new Intent(DeleteKategori.this, KategoriFragment.class));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pd.cancel();
Log.d("volley", "error : " + error.getMessage());
Toast.makeText(DeleteKategori.this, "ERROR DELETE DATA", Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
map.put("id_kategori",deleteID.getText().toString());
return map;
}
};
AppController.getInstance().addToRequestQueue(delReq);
}
}
Code Insert Data
package com.dev.kedaiit.sibooks.ui.kategori;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.dev.kedaiit.sibooks.R;
import com.dev.kedaiit.sibooks.util.AppController;
import com.dev.kedaiit.sibooks.util.ServerAPI;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class InsertKategori extends AppCompatActivity {
EditText id_kategori, kategori;
Button btnBatal, btnSimpan;
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert_kategori);
/*get data from intent*/
Intent data = getIntent();
final int update = data.getIntExtra("update",0);
String intent_idkategori = data.getStringExtra("id_kategori");
String intent_kategori = data.getStringExtra("kategori");
/*end get data from intent*/
// id_kategori = (EditText) findViewById(R.id.idkategori);
kategori = (EditText) findViewById(R.id.edt_kategori);
btnBatal = (Button) findViewById(R.id.btn_cancel);
btnSimpan = (Button) findViewById(R.id.btn_simpan);
pd = new ProgressDialog(InsertKategori.this);
/*kondisi update / insert*/
if(update == 1)
{
btnSimpan.setText("Update Data");
id_kategori.setText(intent_idkategori);
id_kategori.setVisibility(View.VISIBLE);
kategori.setText(intent_kategori);
}
btnSimpan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(update == 1)
{
Update_data();
}else {
simpanData();
}
}
});
btnBatal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent main = new Intent(InsertKategori.this,KategoriFragment.class);
startActivity(main);
}
});
}
private void Update_data()
{
pd.setMessage("Update Data");
pd.setCancelable(true);
pd.show();
StringRequest updateReq = new StringRequest(Request.Method.POST, ServerAPI.URL_UPDATE_KATEGORI,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pd.cancel();
try {
JSONObject res = new JSONObject(response);
Toast.makeText(InsertKategori.this, ""+ res.getString("message") , Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
startActivity( new Intent(InsertKategori.this,KategoriFragment.class));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pd.cancel();
Toast.makeText(InsertKategori.this, "Gagal Insert Data", Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> map = new HashMap<>();
map.put("id_kategori",id_kategori.getText().toString());
map.put("kategori",kategori.getText().toString());
return map;
}
};
AppController.getInstance().addToRequestQueue(updateReq);
}
private void simpanData()
{
pd.setMessage("Menyimpan Data");
pd.setCancelable(true);
pd.show();
StringRequest sendData = new StringRequest(Request.Method.POST, ServerAPI.URL_INSERT_KATEGORI,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pd.cancel();
try {
JSONObject res = new JSONObject(response);
Toast.makeText(InsertKategori.this, ""+ res.getString("message") , Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
startActivity( new Intent(InsertKategori.this,KategoriFragment.class));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pd.cancel();
Toast.makeText(InsertKategori.this, "Gagal Insert Data", Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> map = new HashMap<>();
map.put("id_kategori",id_kategori.getText().toString());
map.put("kategori",kategori.getText().toString());
return map;
}
};
AppController.getInstance().addToRequestQueue(sendData);
}
}
Fragment Kategori
package com.dev.kedaiit.sibooks.ui.kategori;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.dev.kedaiit.sibooks.R;
import com.dev.kedaiit.sibooks.adapter.AdapterDataKategori;
import com.dev.kedaiit.sibooks.model.DataKategori;
import com.dev.kedaiit.sibooks.util.ServerAPI;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class KategoriFragment extends Fragment {
private RecyclerView recyclerView;
private FloatingActionButton floatingActionButton;
private LinearLayoutManager linearLayoutManager;
private DividerItemDecoration dividerItemDecoration;
private List<DataKategori> list;
private RecyclerView.Adapter adapter;
public KategoriFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_kategori, container, false);
recyclerView = view.findViewById(R.id.recyclerViewKategori);
list = new ArrayList<DataKategori>();
adapter = new AdapterDataKategori(getContext(), list);
linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), linearLayoutManager.getOrientation());
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.addItemDecoration(dividerItemDecoration);
recyclerView.setAdapter(adapter);
FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
FloatingActionButton delKtg = (FloatingActionButton) view.findViewById(R.id.delKtg);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), InsertKategori.class);
startActivity(intent);
}
});
delKtg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(),DeleteKategori.class);
startActivity(intent);
}
});
getData();
return view;
}
private void getData() {
final ProgressDialog progressDialog = new ProgressDialog(getContext());
progressDialog.setMessage("Loading...");
progressDialog.show();
JsonObjectRequest my_request = new JsonObjectRequest(Request.Method.GET, ServerAPI.URL_DATA_KATEGORI, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try{
JSONArray jsonArray = response.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject Jobj = jsonArray.getJSONObject(i);
DataKategori obj = new DataKategori();
obj.setId_kategori(Jobj.getString("id_kategori"));
obj.setKategori(Jobj.getString("kategori"));
list.add(obj);
}
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
}
adapter.notifyDataSetChanged();
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error: " + error.getMessage());
progressDialog.dismiss();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(my_request);
}
}
https://github.com/bellabeen/sibooks-client This project me get this in the logcat and when i dont get error code
Your code is almost fine. You just missed one thing. You did not initialize VolleyRequest. Inside simponData and UpdateData methods write this line at the bottom.
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(my_request);
instead of AppController.getInstance().addToRequestQueue(updateReq).
other thing is you are calling the fragment in intent from when response is received .You should call onbackPress() when result is recieved successfully.
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pd.cancel();
try {
JSONObject res = new JSONObject(response);
Toast.makeText(InsertKategori.this, ""+ res.getString("message") , Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
onBackPressed();
}
},
It will restore the previous fragment. In order to update the KategoriFragment view when successful response is received, you can call the getData() method in onResume() method instead of oncreate(). it will call this method whenever fragment is visible to the use

My app crashes when using OkHttp

When I'm trying to send post request using OkHttp, the app on my phone (LG g3) crashes without an error.
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
RequestBody body = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), "login=test&pasword=test");
Request request = new Request.Builder()
.url("http://myUrl")
.post(body)
.build();
try {
Response response = client.newCall(request).execute();
txtRequest.setText(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
});
What am I doing wrong?
you are executing the network call on main thread, this is the exception i guess you are getting. Use AsyncTask and your problem is solved. here is corrected version of your code.
Edited
package com.example.nisu.postrequest;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class SendPost extends AppCompatActivity {
Button btnSend;
TextView txtRequest;
OkHttpClient client = new OkHttpClient();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_post);
btnSend = (Button) findViewById(R.id.btnSend);
txtRequest = (TextView) findViewById(R.id.txtRequest);
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Request request = new Request.Builder()
.url("http://httpbin.org/ip").get()
.build();
new MyAsyncTask().execute(request);
}
});
}
class MyAsyncTask extends AsyncTask<Request, Void, Response> {
#Override
protected Response doInBackground(Request... requests) {
Response response = null;
try {
response = client.newCall(requests[0]).execute();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(Response response) {
super.onPostExecute(response);
try {
txtRequest.setText(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Json parse work on inner class but doesn't work on separate class

I want to display JSON data in textView and i do that but the problem is when i create a separate class for lood JSON data and Store into A ArrayList, it doesn"t work.
Here is my code please help me what i can do to solve that problem.
My inner class code
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.example.mdashikurrahman.transactions.AppController;
import com.example.mdashikurrahman.transactions.HouseOrPerson;
import com.example.mdashikurrahman.transactions.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class InsertActivity extends Activity {
ArrayList<HouseOrPerson> arrayList= new ArrayList<>();
// json array response url
private String urlJsonArry = "http://testgarciaplumbing.3eeweb.com/ashik/select.php";
private Button btnMakeArrayRequest;
private TextView txtResponse;
// temporary string to show the parsed response
private String jsonResponse="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert);
btnMakeArrayRequest = (Button) findViewById(R.id.btnArrayRequest);
txtResponse = (TextView) findViewById(R.id.txtResponse);
btnMakeArrayRequest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
makeJsonArrayRequest();
}
});
}
/**
* Method to make json array request where response starts with [
* */
private void makeJsonArrayRequest() {
JsonArrayRequest req = new JsonArrayRequest(Request.Method.POST, urlJsonArry, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
HouseOrPerson houseOrPerson =new HouseOrPerson(person.getInt("house_id"),
person.getString("house_name"), person.getInt("balance"));
arrayList.add(houseOrPerson);
}
for (int x=0; x<arrayList.size(); x++){
jsonResponse +=Integer.toString(arrayList.get(x).getId())
+ arrayList.get(x).getName()
+ Integer.toString(arrayList.get(x).getBalance())+ "\n\n";
}
txtResponse.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
}
Separate class code
BackgroundTask
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by MD ASHIKUR RAHMAN on 9/24/2016.
*/
public class BackgroundTask {
ArrayList<HouseOrPerson> arrayList= new ArrayList<>();
// json array response url
private String urlJsonArry = "http://testgarciaplumbing.3eeweb.com/ashik/select.php";
/**
* Method that return a arraylist which made by jsonArray
* */
public ArrayList<HouseOrPerson> makeJsonArrayRequest() {
JsonArrayRequest req = new JsonArrayRequest(Request.Method.POST, urlJsonArry, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
HouseOrPerson houseOrPerson =new HouseOrPerson(person.getInt("house_id"),
person.getString("house_name"), person.getInt("balance"));
arrayList.add(houseOrPerson);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
return arrayList;
}
}
InsertActivity class where i create a object ob BackGround class and call makeJsonArrayRequest method
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.example.mdashikurrahman.transactions.BackgroundTask;
import com.example.mdashikurrahman.transactions.HouseOrPerson;
import com.example.mdashikurrahman.transactions.R;
import java.util.ArrayList;
public class InsertActivity extends Activity {
ArrayList<HouseOrPerson> arrayList= new ArrayList<>();
private Button btnMakeArrayRequest;
private TextView txtResponse;
// temporary string to show the parsed response
private String jsonResponse="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert);
btnMakeArrayRequest = (Button) findViewById(R.id.btnArrayRequest);
txtResponse = (TextView) findViewById(R.id.txtResponse);
btnMakeArrayRequest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BackgroundTask bg = new BackgroundTask();
arrayList=bg.makeJsonArrayRequest();
for (int x=0; x<arrayList.size(); x++){
jsonResponse +=Integer.toString(arrayList.get(x).getId())
+ arrayList.get(x).getName()
+ Integer.toString(arrayList.get(x).getBalance())+ "\n\n";
}
txtResponse.setText(jsonResponse);
}
});
}
}
Arent you missing a constructor in your BackgroundTask?
Try putting System.out.println(arrayList.size()) before you return it in your BackgroundTask. What is the size of it?

Categories

Resources