Это мой MainActivity.Java. Я удалил строку API, но знаю, что она правильная, поскольку я проверял ее в почтальоне
Код: Выделить всё
package com.example.foodstore;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import com.android.volley.Cache;
import com.android.volley.Network;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.HurlStack;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.X509Certificate;
public class MainActivity extends AppCompatActivity implements VolleyCallback {
//Alla globala variabler
ScrollView sV;
LinearLayout pll;
ArrayList
Products = new ArrayList();
//API nyckeln
String key = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_main);
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets;
});
//Hämtar ut de element som ska hanteras
sV = (ScrollView) findViewById(R.id.scrollView);
pll = (LinearLayout) findViewById(R.id.productLayout);
/*Cache cache = new DiskBasedCache(getCacheDir(),1024*1024);
Network network = new BasicNetwork(new HurlStack());
RequestQueue requestQueue = new RequestQueue(cache, network);
requestQueue.start();*/
Cache cache = new DiskBasedCache(getCacheDir(), 1024*1024);
Network network = new BasicNetwork(new HurlStack());
RequestQueue requestQueue = new RequestQueue(cache, network);
requestQueue.start();
//Full api sträng för att hämta ut produkter, limit är 10
String apiString = "" + key;
Log.e("", apiString);
//Skapar en instans av funktionen InternetConnection för att se om vi har uppkoppling
/*InternetConection internetConection = new InternetConection(getApplicationContext());
//Kollar om vi inte har någon uppkoppling och visar en Toast med felmedelande
if(!internetConection.isConnectcted()){
Toast.makeText(getApplicationContext(), "404! No internet connection", Toast.LENGTH_SHORT).show();
}
else{
}*/
APICall apiCall = new APICall();
apiCall.get(requestQueue,this, apiString);
}
//Knappen för att visa alla kategorier
public void category(View view){
}
//Knappen för att visa kundkorgen
public void cart(View view){
}
@Override
public void onSuccess(JSONObject object) {
try {
Log.e("", "fetch");
JSONArray products = object.getJSONArray("products");
for (int i = 0; i < products.length(); i++){
String name = products.getJSONObject(i).get("name").toString();
String category = products.getJSONObject(i).get("category").toString();
double price = Double.parseDouble(products.getJSONObject(i).get("price").toString());
//Skapar ett objekt utifrån klassen Food med värden från API:et
Product product = new Product(name, category, price);
//Lägger till objektet i listan food
Products.add(product);
}
//Log.e("", "Antal produkter: " + String.valueOf(Products.size()));
for(int i = 0; i < Products.size(); i ++){
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
ll.setBackgroundColor(Color.WHITE);
ll.setPadding(10,10,10,10);
TextView tW = new TextView(this);
tW.setTextSize(20);
tW.setText(Products.get(i).getName());
ll.addView(tW);
TextView tW2 = new TextView(this);
tW2.setTextSize(15);
tW2.setText("Category: " + Products.get(i).getCategory());
ll.addView(tW2);
TextView tW3 = new TextView(this);
tW3.setTextSize(12);
tW3.setText("Price: " + String.valueOf(Products.get(i).getPrice()) + "kr");
ll.addView(tW3);
Button btn = new Button(this);
btn.setText("add to cart ");
//Sätter params för knappen
//Från tråden https://stackoverflow.com/questions/4641072/how-to-set-layout-weight-attribute-dynamically-from-code
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
btn.setLayoutParams(params);
btn.setBackgroundColor(Color.rgb(0, 128, 0));
btn.setPadding(10,0,0,0);
ll.addView(btn);
pll.addView(ll);
}
}
catch (Exception e){
Log.e("", "Error: " + e.getMessage());
}
}
@Override
public void onFailure(Exception e) {
e.printStackTrace();
Log.e("", "Error onFailure: " + e.getMessage());
Toast.makeText(getApplicationContext(), "Faild to fetch data", Toast.LENGTH_SHORT).show();
}
}
Код: Выделить всё
package com.example.foodstore;
import com.android.volley.*;
import com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONObject;
public class APICall {
public void get(RequestQueue requestQueue, VolleyCallback callback, String url){
//public void get(RequestQueue requestQueue, MainActivity callback, Activity2 callback2, Activity3 callback3, Activity4 callback4, String url){
JsonObjectRequest jsonObjectRequest;
jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener() {
@Override
public void onResponse(JSONObject response) {
callback.onSuccess(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
callback.onFailure(error);
}
});
requestQueue.add(jsonObjectRequest);
}
}
Мой appManifest.xml выглядит так
Код: Выделить всё
Код: Выделить всё
plugins {
alias(libs.plugins.android.application)
}
android {
namespace = "com.example.foodstore"
compileSdk = 34
defaultConfig {
applicationId = "com.example.foodstore"
minSdk = 24
targetSdk = 34
versionCode = 1
versionName = "1.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
}
dependencies {
implementation(libs.appcompat)
implementation(libs.material)
implementation(libs.activity)
implementation(libs.constraintlayout)
testImplementation(libs.junit)
androidTestImplementation(libs.ext.junit)
androidTestImplementation(libs.espresso.core)
implementation (libs.volley)
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... ertpathval