I have implemented search function to get details of clients but when i select the searched item it gives me an error of
java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
so on
This is my code i am using Json to search my clients details and storing in array but when i search the data and select it i get the above error. Please help me out .Thank You
public void RunSearchClientService() {
//progressDialog.show();
JsonObjectRequest postRequest = new JsonObjectRequest
(Request.Method.POST, Network.API_URL + "clients/search", api_parameter, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONObject result = ((JSONObject) response.get("data"));
JSONArray clients = (JSONArray) result.get("clients");
JSONArray invoice_lines = (JSONArray) result.get("invoice_lines");
Integer invoice_number = helper_string.optInt(result, "invoice_number");
logoImage = helper_string.optString(result, "logo");
if (invoice_number > 0) {
edit_invoice_number.setText(String.format("%04d", invoice_number));
toolbar.setTitle(String.format("INV-%04d", invoice_number));
}
array_list_clients.clear();
array_clients = new String[clients.length()];
Integer selected_client_index = 0;
if (clients.length() > 0) {
for (int i = 0; i < clients.length(); i++) {
JSONObject obj = clients.getJSONObject(i);
Client client = new Client();
client.Id = obj.optInt("id");
client.UserId = obj.optInt("user_id");
client.Name = helper_string.optString(obj, "name");
client.Reg_Num = obj.optString("reg_num");
client.Email = helper_string.optString(obj, "email");
client.Address1 = helper_string.optString(obj, "address1");
client.Address2 = helper_string.optString(obj, "address2");
client.City = helper_string.optString(obj, "city");
client.State = helper_string.optString(obj, "state");
client.Postcode = helper_string.optString(obj, "postcode");
client.Country = helper_string.optString(obj, "country");
array_list_clients.add(client);
array_clients[i] = client.Name + " " + "Reg No. : "+ client.Reg_Num ;
if (currentInvoice != null && currentInvoice.ClientId == client.Id) {
selected_client_index = i;
currentClient = client;
}
/*if (obj.optInt("invoice_number") > 0)
invoice_number = obj.optInt("invoice_number");*/
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(NewInvoiceActivity.this, R.layout.custom_simple_spinner_item, array_clients);
spinner_client.setAdapter(adapter);
spinner_client.setSelection(selected_client_index);
}
if (invoice_lines.length() > 0) {
for (int i = 0; i < invoice_lines.length(); i++) {
JSONObject obj = invoice_lines.getJSONObject(i);
Item item = new Item();
item.Id = obj.optInt("id");
item.Quantity = obj.optInt("quantity");
item.Name = helper_string.optString(obj, "name");
item.Rate = obj.optDouble("rate");
item.Description = helper_string.optString(obj, "description");
array_list_items.add(item);
}
calculate_total();
setListViewHeightBasedOnChildren(list_items);
}
if (array_list_items_from_intent != null && array_list_items_from_intent.size() > 0) {
for (int i = 0; i < array_list_items_from_intent.size(); i++) {
array_list_items.add(array_list_items_from_intent.get(i));
}
calculate_total();
setListViewHeightBasedOnChildren(list_items);
}
} catch (Exception ex) {
Toast.makeText(NewInvoiceActivity.this, R.string.error_try_again_support, Toast.LENGTH_LONG).show();
}
// if (progressDialog != null && progressDialog.isShowing()) {
// // If the response is JSONObject instead of expected JSONArray
// progressDialog.dismiss();
// }
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
if (progressDialog != null && progressDialog.isShowing()) {
// If the response is JSONObject instead of expected JSONArray
progressDialog.dismiss();
}
NetworkResponse response = error.networkResponse;
if (response != null && response.data != null) {
try {
JSONObject json = new JSONObject(new String(response.data));
// Toast.makeText(NewInvoiceActivity.this, json.has("message") ? json.getString("message") : json.getString("error"), Toast.LENGTH_LONG).show();
} catch (JSONException ex) {
Toast.makeText(NewInvoiceActivity.this, R.string.error_try_again_support, Toast.LENGTH_SHORT).show();
}
} else {
// Toast.makeText(NewInvoiceActivity.this, error != null && error.getMessage() != null ? error.getMessage() : error.toString(), Toast.LENGTH_LONG).show();
}
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("X-API-KEY", MainActivity.api_key);
return params;
}
};
// Get a RequestQueue
RequestQueue queue = MySingleton.getInstance(NewInvoiceActivity.this).getRequestQueue();
//Used to mark the request, so we can cancel it on our onStop method
postRequest.setTag(TAG);
MySingleton.getInstance(NewInvoiceActivity.this).addToRequestQueue(postRequest);
}
I have created an app with two tabs , tab1 as sender (content edittext1 and edittext2 using to enter name and description of listview in the other tab)and tab2 as receiver (content listview),my problem is in get the data out of database and put it into listview ‘ Name and description separated ‘
this is the logcat error :
java.lang.ArrayIndexOutOfBoundsException: length=1; index=1 at twenty_four.way.com.NoteTaker.FragmentTwo.showData(FragmentTwo.java:54) at twenty_four.way.com.NoteTaker.FragmentTwo.onViewCreated(FragmentTwo.java:47)
and this if DB_Sqlite.java :
public boolean insertData(String name, String desc) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put("name", name); contentValues.put("desc", desc); long result = db.insert("mytable", null, contentValues); if (result == -1) return false; else return true; } public ArrayList getAllrecord() { ArrayList arrayList = new ArrayList(); SQLiteDatabase db = this.getReadableDatabase(); Cursor res = db.rawQuery("select * from mytable", null); res.moveToFirst(); while (res.isAfterLast() == false) { String t2 = res.getString(1); String t3 = res.getString(2); arrayList.add(t2); res.moveToNext(); } return arrayList; } }
and this if FragmentTwo.java :
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); db=new DB_Sqllite(getActivity()); listView = (ListView) view.findViewById(R.id.list_view); adapter = new MessageAdapter(getActivity(), arrayList); listView.setAdapter(adapter); showData(); } public void showData() { ArrayList<String> listData = db.getAllrecord(); ArrayList<MessageModel> arrayList = new ArrayList<>(); for (int i=0; i<listData.size()-1; i++) { String Name = listData.get(i).split(" - ")[0];; String Desc =listData.get(i).split(" - ")[1]; MessageModel messageModel = new MessageModel(); messageModel.setTitle(Name); messageModel.setPrio(true,false); arrayList.add(0,messageModel); } MessageAdapter adapter; adapter = new MessageAdapter(getActivity(), arrayList); listView.setAdapter(adapter); } public void displayReceivedData(MessageModel messageModel) { arrayList.add(0, messageModel); adapter.notifyDataSetChanged(); }
What I have tried:
delete
MessageAdapter adapter;
adapter = new MessageAdapter(getActivity(), arrayList);
listView.setAdapter(adapter);
Я создаю приложение для Android, которое состоит из последовательной связи. Я получаю сообщение об ошибке java.lang.ArrayIndexOutOfBoundsException: length = 1; index = 1, пожалуйста, скажите мне, как это исправить
Это мой драйвер USB:
public class UsbDriver {
private final Context mApplicationContext;
private final UsbManager mUsbManager;
@SuppressWarnings("unused")
private final UsbConnectionHandler mConnectionHandler;
private final int VID;
private final int PID;
protected static final String ACTION_USB_PERMISSION = "ch.serverbox.android.USB";
public static int Device_Exception;
public static UsbDevice Device_Details;
public static UsbEndpoint Data_In_End_Point = null;
public static UsbEndpoint Data_Out_End_Point = null;
public static UsbDeviceConnection USB_Device_Connection;
public UsbDriver(Activity parentActivity,UsbConnectionHandler connectionHandler, int vid, int pid) {
mApplicationContext = parentActivity.getApplicationContext();
mConnectionHandler = connectionHandler;
mUsbManager = (UsbManager) mApplicationContext.getSystemService(Context.USB_SERVICE);
VID = 1027;
PID = 24577;
Device_Exception = 0;
// init();
Check_Devices();
}
private void Check_Devices() {
@SuppressWarnings("unused")
int j=0;
HashMap<String, UsbDevice> devlist = mUsbManager.getDeviceList();
Iterator<UsbDevice> deviter = devlist.values().iterator();
Device_Details = null;
if (devlist.size() != 0) {
while (deviter.hasNext()) {
Device_Details = deviter.next();
if (Device_Details.getVendorId() == VID && Device_Details.getProductId() == PID){
if (!mUsbManager.hasPermission(Device_Details)){
onPermissionDenied(Device_Details);
} else {
UsbDeviceConnection conn = mUsbManager.openDevice(Device_Details);
if (!conn.claimInterface(Device_Details.getInterface(1), true)){
return;
}
conn.controlTransfer(0x21, 34, 0, 0, null, 0, 0);
conn.controlTransfer(0x21, 32, 0, 0,new byte[] { (byte) 0x80, 0x25 , 0x00, 0x00,0x00, 0x00, 0x08 }, 7, 0);
USB_Device_Connection=conn;
Data_In_End_Point = null;
Data_Out_End_Point = null;
UsbInterface usbIf = Device_Details.getInterface(1);
for (int i = 0; i < usbIf.getEndpointCount(); i++) {
if (usbIf.getEndpoint(i).getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
if (usbIf.getEndpoint(i).getDirection() == UsbConstants.USB_DIR_IN)
Data_In_End_Point = usbIf.getEndpoint(i);
else
Data_Out_End_Point = usbIf.getEndpoint(i);
}
}
if (Data_In_End_Point == null || Data_Out_End_Point == null)
Device_Exception = 2;
}
break;
}j++;
}
if (Device_Details == null) {
Device_Exception = 3;
return;
}
}
else {
Device_Exception = 1;
return;
}
}
public void onPermissionDenied(UsbDevice d) {
UsbManager usbman = (UsbManager) mApplicationContext.getSystemService(Context.USB_SERVICE);
PendingIntent pi = PendingIntent.getBroadcast(mApplicationContext, 0, new Intent(ACTION_USB_PERMISSION), 0);
mApplicationContext.registerReceiver(mPermissionReceiver,new IntentFilter(ACTION_USB_PERMISSION));
usbman.requestPermission(d, pi);
}
private class PermissionReceiver extends BroadcastReceiver {
private final IPermissionListener mPermissionListener;
public PermissionReceiver(IPermissionListener permissionListener){
mPermissionListener = permissionListener;
}
@Override
public void onReceive(Context context, Intent intent) {
mApplicationContext.unregisterReceiver(this);
if (intent.getAction().equals(ACTION_USB_PERMISSION)) {
if (!intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
mPermissionListener.onPermissionDenied((UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE));
} else {
l("Permission granted");
UsbDevice dev = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (dev != null){
if (dev.getVendorId() == VID && dev.getProductId() == PID) {
Check_Devices() ;
}
}else{
e("device not present!");
}
}
}
}
}
private BroadcastReceiver mPermissionReceiver = new PermissionReceiver(new IPermissionListener() {
@Override
public void onPermissionDenied(UsbDevice d) {
l("Permission denied on " + d.getDeviceId());
}
});
private static interface IPermissionListener {
void onPermissionDenied(UsbDevice d);
}
public final static String TAG = "USBController";
private void l(Object msg) {
Log.d(TAG, ">==<" + msg.toString() + " >==<");
}
private void e(Object msg) {
Log.e(TAG, ">==< " + msg.toString() + " >==<");
}
}
Это мой обработчик соединения usb
public interface UsbConnectionHandler {
void onUsbStopped();
void onErrorLooperRunningAlready();
void onDeviceNotFound();
}
Это моя основная деятельность:
public class MainActivity extends Activity {
EditText communication_data;
Button send;
public static final int targetVendorID = 1027;
public static final int targetProductID = 24577;
public UsbManager manager;
public UsbDeviceConnection usbDeviceConnection;
public UsbInterface usbInterfaceFound = null;
public UsbEndpoint endpointOut = null;
public UsbEndpoint endpointIn = null;
public UsbDevice usbdevice,device_details;
public UsbEndpoint listusbendpoint;
private static final int VID = 1027;
private static final int PID = 24577;
@SuppressWarnings("unused")
private static UsbDriver Usb_Driver_class;
ActionBar actionbar;
UsbConnectionHandler connectionHandler;
public static UsbDriver USB_Driver_Child;
public static boolean Communication_Failed,Frame_Ok,Total_Frame_Decoded;
static byte[] Communication_Byte;
HashMap<String, UsbDevice> devicelist= null;
static byte[] sample;
static boolean Communication_Ok;
static int Sequence_No,Response_Time;
Thread Receive;
ByteBuffer buffer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//communication_data = (EditText)findViewById(R.id.editText_comm);
send = (Button)findViewById(R.id.button1_sendin);
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Communication_Byte=new byte[1];
if(Check_Devices_Available()==true) {
int Packet_Size = USB_Driver_Child.Data_In_End_Point.getMaxPacketSize();
Toast.makeText(MainActivity.this,""+Packet_Size, Toast.LENGTH_LONG).show();
Receive.start();
Communication_Ok=false;
for(int i=0;(i<5 && Communication_Ok!=true);i++)
Send_Communication_Check_Command();
if(Communication_Ok)
Toast.makeText(MainActivity.this, "Communication Successfully Established", 1000).show();
else
Toast.makeText(MainActivity.this, "Communication Failure", 10000).show();
}
}
private boolean Check_Devices_Available() {
Usb_Driver_class = new UsbDriver(MainActivity.this, connectionHandler, VID, PID);
if(USB_Driver_Child.Device_Exception==0){
if(USB_Driver_Child.USB_Device_Connection==null || USB_Driver_Child.Data_Out_End_Point==null)
return false;
Toast.makeText(MainActivity.this,"Device Found", 1000).show();
return true;
}else if(USB_Driver_Child.Device_Exception==1){
Toast.makeText(MainActivity.this,"No Devices Attached ", Toast.LENGTH_LONG).show();
return false;
}else if(USB_Driver_Child.Device_Exception==2){
Toast.makeText(MainActivity.this,"Device Found,But No End Points", Toast.LENGTH_LONG).show();
return false;
}else if(USB_Driver_Child.Device_Exception==3){
Toast.makeText(MainActivity.this,"Unable to Open Device", Toast.LENGTH_LONG).show();
return false;
}
return false;
}
Thread Receive = new Thread(new Runnable(){
@SuppressWarnings("unused")
@Override
public void run() {
Sequence_No=0;
buffer = ByteBuffer.allocate(64);
sample = new byte[64];
int Frame_Size;
UsbRequest request = new UsbRequest();
int i,j;
byte [] datarx=new byte[1];
char q;
while (true) {
request.initialize(UsbDriver.USB_Device_Connection, UsbDriver.Data_In_End_Point);
request.queue(buffer, 64);
if (UsbDriver.USB_Device_Connection.requestWait() == request) {
sample=buffer.array();
for(i=0;i<64;i++){
if(sample[i]=='&'){
Communication_Ok=true;
break;
}else if(sample[i]==0x03){
if(sample[0]==0x02)
//Frame_Ok=true;
break;
}
}
if(Frame_Ok==true){
//Frame_Ok=false;
//if(sample[1]==1)
//Coil_No=1;
//else
//Coil_No=2;
//Response_Time= (int)(((sample[2]&0x00FF)<<8) + (sample[3]&0x00FF));
//Total_Frame_Decoded=true;
//sample = null;
}
}
}
}
});
private void Send_Communication_Check_Command() {
long i,j;
Communication_Byte[0]='&';
UsbDriver.USB_Device_Connection.bulkTransfer(UsbDriver.Data_Out_End_Point,Communication_Byte, 1, 0);
for(i=0;(i<1000 && Communication_Ok!=true) ;i++)
for(j=0;(j<1000 && Communication_Ok!=true);j++);
}
});
}
}
Это мой логарифм:
E/AndroidRuntime(2452): FATAL EXCEPTION: main
E/AndroidRuntime(2452): java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
E/AndroidRuntime(2452): at android.hardware.usb.UsbDevice.getInterface(UsbDevice.java:155)
E/AndroidRuntime(2452): at com.developer.milancomm.UsbDriver.Check_Devices(UsbDriver.java:74)
E/AndroidRuntime(2452): at com.developer.milancomm.UsbDriver.<init>(UsbDriver.java:48)
E/AndroidRuntime(2452): at com.developer.milancomm.MainActivity$1.Check_Devices_Available(MainActivity.java:86)
E/AndroidRuntime(2452): at com.developer.milancomm.MainActivity$1.onClick(MainActivity.java:63)
E/AndroidRuntime(2452): at android.view.View.performClick(View.java:4240)
E/AndroidRuntime(2452): at android.view.View$PerformClick.run(View.java:17721)
E/AndroidRuntime(2452): at android.os.Handler.handleCallback(Handler.java:730)
E/AndroidRuntime(2452): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(2452): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(2452): at android.app.ActivityThread.main(ActivityThread.java:5103)
E/AndroidRuntime(2452): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(2452): at java.lang.reflect.Method.invoke(Method.java:525)
E/AndroidRuntime(2452): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
E/AndroidRuntime(2452): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
E/AndroidRuntime(2452): at dalvik.system.NativeStart.main(Native Method)
У меня есть массив в формате province;capital
.
provArray = new String[] { "Alberta;Edmonton", "British Columbia;Victoria", "Manitoba;Winnipeg", "New Brunswick:Fredericton",
"Newfoundland and Labrador;St.John's", "Nova Scotia;Halifax", "Ontario;Toronto", "Prince Edward Island;Charlottetown",
"Quebec;Quebec City", "Saskatchewan;Regina", "Northwest Territories;Yellowknife", "Nunavut;Iqaluit", "Yukon;Whitehorse",
"Alabama;Montgomery", "Alaska;Juneau", "Arizona;Phoenix", "Arkansas;Little Rock", "California;Sacramento", "Colorado;Denver",
"Connecticut;Hartford"};
Затем у меня есть цикл for, который отделяет провинции от столицы (до и после «;»). Но по какой-то причине я получаю ошибку, java.lang.ArrayIndexOutOfBoundsException: length=1; index=1
.
for(int k = 0; k < bonusArray.length; k++){
String[] split = bonusArray[k].split(";");
String prov = split[0];
String cap = split[1];
if(prov.equals(answer)){
bonusAnswer = cap;
}
}
Как исправить эту ошибку?
Редактировать: Исправлено, я случайно поместил :
вместо ;
для одного из элементов массива.
5 ответов
Лучший ответ
В массиве есть значения, которые не имеют ;
(точка с запятой), например New Brunswick:Fredericton
Так что этот код
String[] split = bonusArray[k].split(";");
дает массив длины = 1
И это вызывает исключительную ситуацию String cap = split[1];
, потому что вы можете получить доступ только к split[0]
(запомните length = 1).
Итак, вы должны убедиться, что каждый элемент в массиве имеет ;
, или вы проверяете длину переменной split
, прежде чем получить доступ к их значениям.
3
lealceldeiro
25 Окт 2018 в 20:41
String[] split = bonusArray[k].split(";");
Вы просто предполагаете, что вы всегда получите переменную split
с 2 элементами. В этом случае ваш вход имеет несколько элементов, которые не возвращают 2 элемента при разбиении, split()
на самом деле не возвращает 2 элемента, поэтому ArrayIndexOutOfBoundsException
.
Всегда проверяйте «длину массива» перед доступом к его элементам по указанному индексу.
РЕДАКТИРОВАТЬ: «New Brunswick: Fredericton», вызывающий split(";")
для этой строки, не вернет 2 элемента.
1
kosa
25 Окт 2018 в 20:44
Мы можем сделать это несколькими способами, но лучше всего использовать split.length-1
вместо того, чтобы задавать жестко закодированное значение в качестве индекса. Используя это, вы никогда не получите это исключение, даже если длина массива равна 1.
for(int k = 0; k < bonusArray.length; k++){
String[] split = bonusArray[k].split(";");
String prov = split[0];
String cap = split[split.length-1];
if(prov.equals(answer)){
bonusAnswer = cap;
}
}
0
Tayyab Razaq
25 Окт 2018 в 21:12
«Нью-Брансуик: Фредериктон» не содержит «;» , Попробуйте встроить split () и часть [0], [1] в блок try-catch, чтобы исключить возникновение исключения OutOfBoundsException.
0
FeniX-
25 Окт 2018 в 21:04
У вас есть опечатка в «Нью-Брансуик: Фредериктон», вам нужна точка с запятой против обычной двоеточия
2
arcscp
25 Окт 2018 в 20:37
I am pretty new to docker, but I don’t think I should be seeing go errors as an end user, so I am notifying the community of this bug.
I updated Docker, to version: v2.0.0-rc.1, and then started getting: panic: runtime error: index out of range [1] with length 1, followed by some «go» errors when running docker-compose up. After searching on here, I found similar error messages with using 0 replicas docker/compose-cli#1935, but the error is different (1 instead of 0), and I wasn’t using replicas — unless I am missing something.
Ultimately I ended up using 0 replicas as a workaround to get a proper error message, which was that I had background containers running.
My guess is that something similar to docker/compose-cli#1935 can be implemented to prevent these errors as well.
Steps to reproduce the issue:
- Updated to version: v2.0.0-rc.1
- Had containers running in the background
- ran «docker-compose up» with this docker-compose.yml file:
services:
api:
container_name: api
build:
context: .
dockerfile: api/Dockerfile.api
image: mutcompute-api
ports:
— «5000:5000»
volumes:
— ./api:/app/
environment:
— MAIL_SERVER=email
— MAIL_PORT=8025
command: gunicorn -b 0.0.0.0:5000 api:app
client:
container_name: client
build:
context: .
dockerfile: client/Dockerfile.client
image: mutcompute-client
ports:
— «3000:3000»
volumes:
— ./client:/app/
email:
container_name: email
build:
context: .
dockerfile: api/Dockerfile.api
image: mutcompute-api
ports:
— «8025:8025»
command: python -m smtpd -n -c DebuggingServer 0.0.0.0:8025
Describe the results you received:
panic: runtime error: index out of range [1] with length 1
goroutine 37 [running]:
github.com/docker/compose-cli/pkg/compose.(*convergence).ensureService(0xc00027ff20, 0x2120ba8, 0xc000454450, 0xc000240f00, 0xc0001ce7c8, 0x3, 0x0, 0x0, 0x0, 0xc000240a00, …)
github.com/docker/compose-cli/pkg/compose/convergence.go:222 +0x11f1
github.com/docker/compose-cli/pkg/compose.(*convergence).apply.func1(0x2120ba8, 0xc000454450, 0xc0001ce7c8, 0x3, 0x0, 0x0)
github.com/docker/compose-cli/pkg/compose/convergence.go:99 +0x21f
github.com/docker/compose-cli/pkg/compose.run.func1(0x0, 0x0)
github.com/docker/compose-cli/pkg/compose/dependencies.go:102 +0xa3
golang.org/x/sync/errgroup.(*Group).Go.func1(0xc000590540, 0xc000626180)
golang.org/x/sync@v0.0.0-20210220032951-036812b2e83c/errgroup/errgroup.go:57 +0x59
created by golang.org/x/sync/errgroup.(*Group).Go
golang.org/x/sync@v0.0.0-20210220032951-036812b2e83c/errgroup/errgroup.go:54 +0x66
Describe the results you expected:
Error response from daemon: driver failed programming external connectivity on endpoint <…> Bind for 0.0.0.0:5000 failed: port is already allocated
Additional information you deem important (e.g. issue happens only occasionally):
Heres my SO post:
https://stackoverflow.com/questions/68900909/docker-compose-error-panic-runtime-error-index-out-of-range-1-with-length?noredirect=1#comment121769539_68900909
And an exerpt:
How I fixed it:
I switched to a previous version without db service and was prompted to run docker-compose —remove -orphans, which didn’t really do much. After searching through GitHub issues, and seeing most of the issues were related to replicas, I decided what the heck and added a replica section to the api service. While this error had nothing to do with replicas, I was able to get a different error:
WARNING: The «api» service is using the custom container name «api». Docker requires each container to have a unique name. Remove the custom name to scale the service.
for this error, I just commented out all the container_name sections in each service, and got a new error:
Error response from daemon: driver failed programming external connectivity on endpoint <…> Bind for 0.0.0.0:5000 failed: port is already allocated
Boom! this was the real issue. Searched SO for this, and found out I just needed to run docker-compose down
When I switched back to the branch with the db service, all was working!
Output of docker-compose --version
:
Docker Compose version v2.0.0-rc.1
Output of docker version
:
Client:
Cloud integration: 1.0.17
Version: 20.10.8
API version: 1.41
Go version: go1.16.6
Git commit: 3967b7d
Built: Fri Jul 30 19:55:20 2021
OS/Arch: darwin/amd64
Context: default
Experimental: true
Server: Docker Engine - Community
Engine:
Version: 20.10.8
API version: 1.41 (minimum version 1.12)
Go version: go1.16.6
Git commit: 75249d8
Built: Fri Jul 30 19:52:10 2021
OS/Arch: linux/amd64
Experimental: false
containerd:
Version: 1.4.9
GitCommit: e25210fe30a0a703442421b0f60afac609f950a3
runc:
Version: 1.0.1
GitCommit: v1.0.1-0-g4144b63
docker-init:
Version: 0.19.0
GitCommit: de40ad0
Output of docker context show
:
You can also run docker context inspect context-name
to give us more details but don’t forget to remove sensitive content.
Output of docker info
:
Client:
Context: default
Debug Mode: false
Plugins:
buildx: Build with BuildKit (Docker Inc., v0.6.1-docker)
compose: Docker Compose (Docker Inc., v2.0.0-rc.1)
scan: Docker Scan (Docker Inc., v0.8.0)
Server:
Containers: 23
Running: 0
Paused: 0
Stopped: 23
Images: 30
Server Version: 20.10.8
Storage Driver: overlay2
Backing Filesystem: extfs
Supports d_type: true
Native Overlay Diff: true
userxattr: false
Logging Driver: json-file
Cgroup Driver: cgroupfs
Cgroup Version: 1
Plugins:
Volume: local
Network: bridge host ipvlan macvlan null overlay
Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog
Swarm: inactive
Runtimes: io.containerd.runc.v2 io.containerd.runtime.v1.linux runc
Default Runtime: runc
Init Binary: docker-init
containerd version: e25210fe30a0a703442421b0f60afac609f950a3
runc version: v1.0.1-0-g4144b63
init version: de40ad0
Security Options:
seccomp
Profile: default
Kernel Version: 5.10.47-linuxkit
Operating System: Docker Desktop
OSType: linux
Architecture: x86_64
CPUs: 4
Total Memory: 1.939GiB
Name: docker-desktop
ID: AJ7X:ZSOB:YBIX:AXRV:UMDE:5E3J:UJK4:DHD7:743K:M4TV:SCYI:QXBS
Docker Root Dir: /var/lib/docker
Debug Mode: true
File Descriptors: 42
Goroutines: 43
System Time: 2021-08-30T23:36:08.470272Z
EventsListeners: 3
HTTP Proxy: http.docker.internal:3128
HTTPS Proxy: http.docker.internal:3128
Registry: https://index.docker.io/v1/
Labels:
Experimental: false
Insecure Registries:
127.0.0.0/8
Live Restore Enabled: false
Additional environment details (AWS ECS, Azure ACI, local, etc.):
Local environment